https://wanago.io/2019/12/23/javascript-design-patterns-4-decorators-and-their-implementation-in-typescript/
function excludeProperties(propertiesToExclude: string[]) {
return (target: any, propertyName: string, descriptor: PropertyDescriptor) => {
const originalFunction = descriptor.value;
descriptor.value = async function(...args: any[]) {
const originalResult = await originalFunction.apply(this, args);
propertiesToExclude.forEach(propertyName => {
delete originalResult[propertyName];
});
return originalResult;
};
}
}
import userModel from './user.model';
import UserNotFoundException from './UserNotFoundException';
import excludeProperties from './excludeProperties';
class UserService {
private user = userModel;
@excludeProperties(['password'])
private getUser = async (userId: string) => {
const user = await this.user.findById(userId);
if (user) {
return user;
}
throw new UserNotFoundException(userId);
}
}
Comments
Post a Comment