import "reflect-metadata"; import { MongoSchema } from "../MongoSchema"; import { MongoSchemaRegistry } from "../MongoSchemaRegistry"; import { SchemaFieldValidationError } from "./SchemaValidationResult"; import { MongoSchemaField } from "../MongoSchema"; export class SchemaValidator { static validateField(field: MongoSchemaField, data: any): Error { // Ignore _id field (It's managed by mongo) if(field.name == "_id") return null; if(data === undefined || data === null) { if(field.options.required) { return new Error("Field '" + field.name + "' is required but it's value is: " + data); } } if(data && data.constructor.name !== field.type) { if(!field.getReferencedCollection()) { return new Error("Field '" + field.name + "' has invalid type. '" + field.type + "' is needed but '" + data.constructor.name + "' was given."); } } let childSchema = MongoSchemaRegistry.getSchema(field.getType()) if(childSchema) { return childSchema.validate(data); } return null; } };