42 lines
774 B
TypeScript
Raw Normal View History

2023-04-27 23:18:48 +02:00
import { eq } from 'lodash/fp';
2023-04-27 23:18:48 +02:00
interface Options {
name: string;
validator?(config: unknown): void;
handler(...args: any[]): any;
}
const createPolicy = (options: Options) => {
const { name = 'unnamed', validator, handler } = options;
2023-04-27 23:18:48 +02:00
const wrappedValidator = (config: unknown) => {
if (validator) {
try {
validator(config);
} catch (e) {
throw new Error(`Invalid config passed to "${name}" policy.`);
}
}
};
return {
name,
validator: wrappedValidator,
handler,
};
};
2023-04-27 23:18:48 +02:00
const createPolicyContext = (type: string, ctx: object) => {
2021-09-24 09:35:25 +02:00
return Object.assign(
{
is: eq(type),
get type() {
return type;
},
},
ctx
);
};
export { createPolicy, createPolicyContext };