UNPKG

fastest-validator-nestjs

Version:
176 lines (175 loc) 7.76 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.FastestValidatorExceptionFilter = exports.FastestValidatorPipe = exports.FastestValidationException = exports.NestedObject = exports.EqualTo = exports.Any = exports.ArrayOf = exports.Enum = exports.Date = exports.Email = exports.ObjectId = exports.UUID = exports.Numeric = exports.Boolean = exports.Alphabet = exports.Field = exports.decoratorFactoryArray = exports.decoratorFactory = exports.ValidationSchema = exports.getCompiled = exports.getInnerSchema = exports.getSchema = exports.helloFvn = void 0; require("reflect-metadata"); const load_package_util_1 = require("@nestjs/common/utils/load-package.util"); const common_1 = require("@nestjs/common"); const FastestValidator = load_package_util_1.loadPackage('fastest-validator', 'f-v-decorators'); const logger = new common_1.Logger('FastestValidation', true); function helloFvn() { return "hello fastest validation nestjs"; } exports.helloFvn = helloFvn; const SCHEMA_KEY = Symbol("propertyMetadata"); const COMPILE_FUNC = Symbol("compiler"); function getSchema(target) { return Reflect.getMetadata(SCHEMA_KEY, target.prototype); } exports.getSchema = getSchema; function getInnerSchema(target) { const schema = Reflect.getMetadata(SCHEMA_KEY, target.prototype); delete schema['$$strict']; return schema; } exports.getInnerSchema = getInnerSchema; function getCompiled(target, messages = {}) { let compiled = Reflect.getMetadata(COMPILE_FUNC, target.prototype); if (!compiled) { logger.log("Compile schema of " + target.name, "FastestValidator"); const v = new FastestValidator({ useNewCustomCheckerFunction: true, messages }); const s = Reflect.getMetadata(SCHEMA_KEY, target.prototype) || {}; Reflect.defineMetadata(COMPILE_FUNC, v.compile(s), target.prototype); compiled = Reflect.getMetadata(COMPILE_FUNC, target.prototype); } return compiled; } exports.getCompiled = getCompiled; const updateSchema = (target, key, options) => { const schema = Reflect.getMetadata(SCHEMA_KEY, target) || {}; schema[key] = options; Reflect.defineMetadata(SCHEMA_KEY, schema, target); }; function ValidationSchema({ strict = false, messages = {}, condition = null } = {}) { return function _Schema(target) { updateSchema(target.prototype, "$$strict", strict); if (condition !== null) { updateSchema(target.prototype, "condition", { custom: condition, type: "custom", optional: true, }); } getCompiled(target, messages); return target; }; } exports.ValidationSchema = ValidationSchema; exports.decoratorFactory = (mandatory = {}, defaults = {}) => { return function (options = {}) { return (target, key) => { updateSchema(target, key, Object.assign(Object.assign(Object.assign({}, defaults), options), mandatory)); }; }; }; exports.decoratorFactoryArray = (mandatory = {}, defaults = {}) => { return function (options = {}) { if (typeof options.items == 'function') { options.items = { type: "object", props: getInnerSchema(options.items) }; } return (target, key) => { updateSchema(target, key, Object.assign(Object.assign(Object.assign({}, defaults), options), mandatory)); }; }; }; exports.Field = exports.decoratorFactory({}, {}); exports.Alphabet = exports.decoratorFactory({ type: "string" }, { empty: false }); exports.Boolean = exports.decoratorFactory({ type: "boolean" }); exports.Numeric = exports.decoratorFactory({ type: "number" }, { convert: true }); exports.UUID = exports.decoratorFactory({ type: "uuid" }); exports.ObjectId = exports.decoratorFactory({ type: "string" }, { pattern: /^[a-f\d]{24}$/i, messages: { stringPattern: "The '{field}' field is not a valid objectId" } }); exports.Email = exports.decoratorFactory({ type: "email" }); exports.Date = exports.decoratorFactory({ type: "date" }); exports.Enum = exports.decoratorFactory({ type: "enum" }); exports.ArrayOf = exports.decoratorFactoryArray({ type: "array" }); exports.Any = exports.decoratorFactory({ type: "any" }); exports.EqualTo = exports.decoratorFactory({ type: "equal" }); function NestedObject(options = {}) { return (target, key) => { const t = Reflect.getMetadata("design:type", target, key); const props = Object.assign({}, getSchema(t)); const strict = props.$$strict || false; delete props.$$strict; updateSchema(target, key, Object.assign(Object.assign({}, options), { props, strict, type: "object" })); }; } exports.NestedObject = NestedObject; class FastestValidationException extends Error { constructor(errors) { super(); this.errors = null; this.status = 400; this.code = 4000; this.errors = errors; this.message = "Validation failed"; } getStatus() { return this.status; } } exports.FastestValidationException = FastestValidationException; let FastestValidatorPipe = class FastestValidatorPipe { transform(value, metadata) { if (metadata.metatype.name === "Object") { return value; } ; const compiled = getCompiled(metadata.metatype); const result = compiled(value); if (result !== true) { throw new FastestValidationException(this.formatErrors(result, metadata.type)); } else { delete value.condition; return value; } } formatErrors(errors = [], type) { return Object.assign({}, ...errors.map(error => { return { [error.field || "forbiddenKeys"]: error.message .replace("field", `field in ${type}`) .replace("'' ", "") }; })); } }; FastestValidatorPipe = __decorate([ common_1.Injectable() ], FastestValidatorPipe); exports.FastestValidatorPipe = FastestValidatorPipe; let FastestValidatorExceptionFilter = class FastestValidatorExceptionFilter { constructor(options) { this.options = options; } catch(exception, host) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const request = ctx.getRequest(); const status = exception.getStatus(); const env = process.env.NODE_ENV; return response .status(status) .json(Object.assign(Object.assign({ status: status, message: exception.message }, (this.options.showStack && { stack: exception.stack })), { payload: exception.errors })); } }; FastestValidatorExceptionFilter = __decorate([ common_1.Catch(FastestValidationException), __metadata("design:paramtypes", [Object]) ], FastestValidatorExceptionFilter); exports.FastestValidatorExceptionFilter = FastestValidatorExceptionFilter;