json-api-nestjs
Version:
JsonApi Plugin for NestJs
81 lines • 3.89 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.bindController = bindController;
const common_1 = require("@nestjs/common");
const constants_1 = require("@nestjs/common/constants");
const route_paramtypes_enum_1 = require("@nestjs/common/enums/route-paramtypes.enum");
const bindings_1 = require("../config/bindings");
const constants_2 = require("../../../constants");
function bindController(controller, entity, config) {
for (const methodName in bindings_1.Bindings) {
const { name, path, parameters, method, implementation } = bindings_1.Bindings[methodName];
const decoratorOptions = Reflect.getMetadata(constants_2.JSON_API_DECORATOR_OPTIONS, controller);
if (decoratorOptions) {
const { allowMethod = Object.keys(bindings_1.Bindings) } = decoratorOptions;
if (!allowMethod.includes(name))
continue;
}
if (!Object.prototype.hasOwnProperty.call(controller.prototype, name)) {
// need uniq descriptor for correct work swagger
Reflect.defineProperty(controller.prototype, name, {
value: function (...arg) {
return this.constructor.__proto__.prototype[name].call(this, ...arg);
},
writable: true,
enumerable: false,
configurable: true,
});
}
const descriptor = Reflect.getOwnPropertyDescriptor(controller.prototype, name);
if (!descriptor) {
throw new Error(`Descriptor for "${controller.name}[${name}]" is undefined`);
}
switch (method) {
case common_1.RequestMethod.GET: {
(0, common_1.Get)(path)(controller.prototype, name, descriptor);
break;
}
case common_1.RequestMethod.DELETE: {
(0, common_1.HttpCode)(204)(controller.prototype, name, descriptor);
(0, common_1.Delete)(path)(controller.prototype, name, descriptor);
break;
}
case common_1.RequestMethod.POST: {
(0, common_1.Post)(path)(controller.prototype, name, descriptor);
break;
}
case common_1.RequestMethod.PATCH: {
(0, common_1.Patch)(path)(controller.prototype, name, descriptor);
break;
}
default: {
throw new Error(`Method '${method}' unsupported`);
}
}
const paramsMetadata = Reflect.getMetadata(constants_1.ROUTE_ARGS_METADATA, controller.prototype.constructor, name);
for (const key in parameters) {
const parameter = parameters[key];
const { property, decorator, mixins } = parameter;
const resultMixin = mixins.map((mixin) => mixin(entity, config));
if (paramsMetadata) {
let typeDecorator;
switch (decorator) {
case common_1.Query:
typeDecorator = route_paramtypes_enum_1.RouteParamtypes.QUERY;
break;
case common_1.Param:
typeDecorator = route_paramtypes_enum_1.RouteParamtypes.PARAM;
break;
case common_1.Body:
typeDecorator = route_paramtypes_enum_1.RouteParamtypes.BODY;
}
const tmp = Object.entries(paramsMetadata)
.filter(([k, v]) => k.split(':').at(0) === typeDecorator.toString())
.reduce((acum, [k, v]) => (acum.push(...v.pipes), acum), []);
resultMixin.push(...tmp);
}
decorator(property, ...resultMixin)(controller.prototype, name, parseInt(key, 10));
}
}
}
//# sourceMappingURL=bind-controller.js.map