UNPKG

@lakutata/core

Version:

Lakutata Framework Core

75 lines 3.38 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Accept = exports.Return = void 0; const InvalidMethodReturnException_1 = require("../exceptions/InvalidMethodReturnException"); const InvalidMethodAcceptException_1 = require("../exceptions/InvalidMethodAcceptException"); const Return = (returnSchema, options = { strict: true, stripUnknown: true }) => { return (target, propertyKey, descriptor) => { descriptor.writable = false; const originalMethod = descriptor.value; returnSchema = returnSchema.label(`Method [${propertyKey}] return value`).nullable(false).required(`Method [${propertyKey}] must return ${returnSchema.type}`); descriptor.value = function (...args) { const originalMethodResult = originalMethod.apply(this, args); if (originalMethodResult instanceof Promise) { return new Promise((resolve, reject) => { return originalMethodResult.then(originalAsyncMethodResult => { try { const methodResult = returnSchema.validateSync(originalAsyncMethodResult, options); resolve(methodResult); } catch (e) { reject(new InvalidMethodReturnException_1.InvalidMethodReturnException(e.message)); } }).catch(reject); }); } else { try { return returnSchema.validateSync(originalMethodResult, options); } catch (e) { if (target['generateException']) { throw target['generateException'](InvalidMethodReturnException_1.InvalidMethodReturnException, e.message); } else { throw new InvalidMethodReturnException_1.InvalidMethodReturnException(e.message); } } } }; return descriptor; }; }; exports.Return = Return; const Accept = (argumentSchemas, options = { strict: false, stripUnknown: true }) => { return (target, propertyKey, descriptor) => { descriptor.writable = false; const originalMethod = descriptor.value; descriptor.value = function (...args) { const schemas = Array.isArray(argumentSchemas) ? argumentSchemas : [argumentSchemas]; try { for (let argumentIndex = 0; argumentIndex < schemas.length; argumentIndex++) { args[argumentIndex] = schemas[argumentIndex].label(`Method [${propertyKey}] accept argument[${argumentIndex}]`).validateSync(args[argumentIndex], options); } } catch (e) { if (target['generateException']) { throw target['generateException'](InvalidMethodAcceptException_1.InvalidMethodAcceptException, e.message); } else { throw new InvalidMethodAcceptException_1.InvalidMethodAcceptException(e.message); } } return originalMethod.apply(this, args); }; return descriptor; }; }; exports.Accept = Accept; //# sourceMappingURL=MethodValidation.js.map