diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 00000000..918034ae --- /dev/null +++ b/src/index.ts @@ -0,0 +1,26 @@ +// Import Internal Dependencies +import { events } from "./utils/index"; + +export interface ValidateEventDataOptions { + name: string; + operation: "CREATE" | "UPDATE" | "DELETE" | "VOID"; + data: Record; +} + +export function validateEventData(options: ValidateEventDataOptions) { + const { name, operation, data } = options; + + if(!events.has(name)) { + throw "Unknown Event"; + } + + const event = events.get(name); + if(!event.has(operation)) { + throw "Unknown \"operation\" for for the specified \"event\""; + } + + const operationValidationFunction = event.get(operation.toLocaleLowerCase()); + if (!operationValidationFunction(data)) { + throw "Wrong data for the specified \"event\" & \"operation\""; + } +} diff --git a/src/utils/index.ts b/src/utils/index.ts new file mode 100644 index 00000000..5ee45297 --- /dev/null +++ b/src/utils/index.ts @@ -0,0 +1,24 @@ +// Import Third-party Dependencies +import Ajv, { ValidateFunction } from "ajv"; + +// Import Internal Dependencies +import * as eventsValidationSchemas from "../schema/index"; + +// CONSTANTS +const ajv = new Ajv(); + +export type OperationFunctions = Record; + +type MappedEvents = Map>> + +export const events: MappedEvents = new Map(); + +for (const [name, validationSchemas] of Object.entries(eventsValidationSchemas)) { + const operationsValidationFunctions: Map> = new Map(); + + for (const [operation, validationSchema] of Object.entries(validationSchemas)) { + operationsValidationFunctions.set(operation, ajv.compile(validationSchema)); + } + + events.set(name, operationsValidationFunctions); +}