UNPKG

ncrudify

Version:

Configurable CRUD module for NestJS and Mongoose.

74 lines 3.43 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Crudify = Crudify; exports.disableRoutes = disableRoutes; const common_1 = require("@nestjs/common"); require("reflect-metadata"); const crudify_routes_1 = require("./crudify.routes"); function Crudify(options) { return function (target) { var _a; const prototype = target.prototype; const basePrototype = Object.getPrototypeOf(prototype); const isSoftDelete = (_a = options.softDelete) !== null && _a !== void 0 ? _a : false; Reflect.defineMetadata("model", options.model, prototype); Reflect.defineMetadata("modelName", options.model.type.name, prototype); disableRoutes(options, prototype, isSoftDelete); const routes = crudify_routes_1.CrudifyRoutes.routes(options); for (const route of routes) { let method = prototype[route.methodName]; if (!method || method === basePrototype[route.methodName]) { method = function (...args) { var _a; return (_a = basePrototype[route.methodName]) === null || _a === void 0 ? void 0 : _a.apply(this, args); }; Object.defineProperty(prototype, route.methodName, { value: method, writable: true, configurable: true, }); } if (isSoftDelete && route.methodName === "delete") { const originalMethod = prototype[route.methodName]; prototype[route.methodName] = async function (...args) { const entity = args[0]; const deleteDto = { deletedAt: new Date() }; return originalMethod.apply(this, [entity, deleteDto]); }; } if (route.parameters) { for (const param of route.parameters) { param.decorator(prototype, route.methodName, param.index); } } const uniqueOperationId = `${target.name}_${route.methodName}`; Reflect.defineMetadata("swagger/apiOperation", { operationId: uniqueOperationId, summary: `Method: ${route.methodName}`, }, prototype, route.methodName); const methodDecorators = [ route.httpMethod(route.path), ...route.decorators, ]; (0, common_1.applyDecorators)(...methodDecorators)(prototype, route.methodName, Object.getOwnPropertyDescriptor(prototype, route.methodName)); } }; } function disableRoutes(options, prototype, isSoftDelete) { var _a, _b; Reflect.defineMetadata("softDelete", isSoftDelete, prototype); if (options.routes === undefined) options.routes = { exclude: [] }; if (((_a = options.routes) === null || _a === void 0 ? void 0 : _a.exclude) === undefined) { options.routes.exclude = []; } if (Array.isArray(options.routes.exclude)) { if ((_b = options.routes) === null || _b === void 0 ? void 0 : _b.disableBulk) { options.routes.exclude.push("createBulk"); options.routes.exclude.push("updateBulk"); options.routes.exclude.push("deleteBulk"); options.routes.exclude.push("restoreBulk"); } } } //# sourceMappingURL=crudify.decorator.js.map