Last active
December 21, 2024 02:42
-
-
Save DanielMPries/57fed3066fa04fcea23886782a49399b to your computer and use it in GitHub Desktop.
NestJs JSON schema validator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Ajv from 'ajv/dist/2020'; | |
import { | |
ValidationArguments, | |
ValidatorConstraint, | |
ValidatorConstraintInterface, | |
ValidatorOptions, | |
registerDecorator, | |
} from 'class-validator'; | |
@ValidatorConstraint({ name: 'isJsonSchema', async: false }) | |
export class IsJsonSchemaConstraint implements ValidatorConstraintInterface { | |
// eslint-disable-next-line @typescript-eslint/no-unused-vars | |
validate(schema: object, args: ValidationArguments) { | |
// ensure that the string is parsable json | |
try { | |
JSON.parse(JSON.stringify(schema)); | |
// eslint-disable-next-line @typescript-eslint/no-unused-vars | |
} catch (e) { | |
return false; | |
} | |
// ensure that the json is a valid json schema | |
const ajv = new Ajv({ strict: false }); | |
const validate = ajv.compile(JSON.parse(JSON.stringify(schema))); | |
if (validate.errors?.length) return false; | |
return true; | |
} | |
// eslint-disable-next-line @typescript-eslint/no-unused-vars | |
defaultMessage(args?: ValidationArguments): string { | |
return 'Schema is not a valid JSON schema'; | |
} | |
} | |
/** | |
* Allows the user to validate that a string is a valid JSON schema as a custom decorator | |
* @example | |
* @IsJsonSchema() | |
* schema: Object; | |
* | |
* @param validationOptions the validation options | |
*/ | |
export function IsJsonSchema(validationOptions?: ValidatorOptions) { | |
return function (object: any, propertyName: string) { | |
registerDecorator({ | |
target: object.constructor, | |
propertyName: propertyName, | |
options: validationOptions, | |
constraints: [], | |
name: 'isJsonSchema', | |
validator: IsJsonSchemaConstraint, | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment