@toss/nestjs-aop
Version:
<!-- PROJECT LOGO --> <br /> <div align="center"> <a href="https://github.com/toss/nestjs-aop"> <img src="https://toss.tech/wp-content/uploads/2022/11/tech-article-nest-js-02.png" alt="Logo" height="200"> </a>
64 lines • 2.67 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDecorator = void 0;
const common_1 = require("@nestjs/common");
const utils_1 = require("./utils");
/**
* @param metadataKey equal to 1st argument of Aspect Decorator
* @param metadata The value corresponding to the metadata of WrapParams. It can be obtained from LazyDecorator's warp method and used.
*/
const createDecorator = (metadataKey, metadata) => {
const aopSymbol = Symbol('AOP_DECORATOR');
return (0, common_1.applyDecorators)(
// 1. Add metadata to the method
(target, propertyKey, descriptor) => {
if (descriptor.get && descriptor.set) {
throw new Error(`createDecorator cannot be applied to '${String(propertyKey)}' because it has both a getter and a setter. ` +
`Separate them into different properties, or use a regular method instead.`);
}
return (0, utils_1.AddMetadata)(metadataKey, {
originalFn: descriptor.value || descriptor.get || descriptor.set,
metadata,
aopSymbol,
})(target, propertyKey, descriptor);
},
// 2. Wrap the method before the lazy decorator is executed
(_, propertyKey, descriptor) => {
const originalFn = descriptor.value || descriptor.get || descriptor.set;
const wrapperFn = function (...args) {
var _a;
const wrappedFn = (_a = this[aopSymbol]) === null || _a === void 0 ? void 0 : _a[propertyKey];
if (wrappedFn) {
// If there is a wrapper stored in the method, use it
return wrappedFn.apply(this, args);
}
// if there is no wrapper that comes out of method, call originalFn
return originalFn.apply(this, args);
};
// Assign wrapper to the appropriate descriptor property
if (descriptor.value !== undefined) {
descriptor.value = wrapperFn;
}
else if (descriptor.get !== undefined) {
descriptor.get = wrapperFn;
}
else if (descriptor.set !== undefined) {
descriptor.set = wrapperFn;
}
/**
* There are codes that using `function.name`.
* Therefore the codes below are necessary.
*
* ex) @nestjs/swagger
*/
Object.defineProperty(wrapperFn, 'name', {
value: propertyKey.toString(),
writable: false,
});
if (originalFn) {
Object.setPrototypeOf(wrapperFn, originalFn);
}
});
};
exports.createDecorator = createDecorator;
//# sourceMappingURL=create-decorator.js.map