Skip to content

Commit

Permalink
feat: event validation
Browse files Browse the repository at this point in the history
  • Loading branch information
Rossb0b committed Mar 29, 2022
1 parent 48f020f commit e0642a5
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Import Internal Dependencies
import { events } from "./utils/index";

export interface ValidateEventDataOptions {
name: string;
operation: "CREATE" | "UPDATE" | "DELETE" | "VOID";
data: Record<string, any>;
}

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\"";
}
}
24 changes: 24 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -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<string, any>;

type MappedEvents = Map<string, Map<string, ValidateFunction<OperationFunctions>>>

export const events: MappedEvents = new Map();

for (const [name, validationSchemas] of Object.entries(eventsValidationSchemas)) {
const operationsValidationFunctions: Map<string, ValidateFunction<OperationFunctions>> = new Map();

for (const [operation, validationSchema] of Object.entries(validationSchemas)) {
operationsValidationFunctions.set(operation, ajv.compile(validationSchema));
}

events.set(name, operationsValidationFunctions);
}

0 comments on commit e0642a5

Please sign in to comment.