konditions
Version:
A simple and customizable JSON-based condition engine in TypeScript (e.g. GreaterThan, StringLike, Every, Some)
47 lines • 2.04 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultEngine = void 0;
const zod_1 = require("./validation/zod");
class DefaultEngine {
constructor(commands) {
this.commands = commands;
}
async evaluate(props) {
// First, let's make sure the input document is valid
// i.e. it must be a plain object having a `type` property with a string value
const inputPropValidation = zod_1.parseInputPropsWithZodAndBuildResponse(props);
if (!inputPropValidation.passed)
return { passed: false, error: inputPropValidation.error };
// Then, let's validate the props for this specific type
const { type, ...rest } = inputPropValidation.props;
// Do we even accept and handle this type?
const condition = this.commands[type];
if (!condition)
return {
passed: false,
error: { type: `UnexpectedError`, message: `Unknown type "${type}"` },
};
if (!condition.validator || typeof condition.validator !== `function`)
return {
passed: false,
error: { type: `UnexpectedError`, message: `Type "${type}" has no validator set` },
};
if (!condition.resolver || typeof condition.resolver !== `function`)
return {
passed: false,
error: { type: `UnexpectedError`, message: `Type "${type}" has no resolver set` },
};
// Validate the extracted props
const conditionPropValidation = await condition.validator(rest, this);
if (!conditionPropValidation.passed)
return { passed: false, error: conditionPropValidation.error };
// Return the resolution
const resolution = await this.commands[props.type].resolver(rest, this);
return resolution;
}
get(type) {
return this.commands[type];
}
}
exports.DefaultEngine = DefaultEngine;
//# sourceMappingURL=engine.default.js.map
;