Recently, I've delved into exploring decorators for TypeScript. Angular showcases a wide array of decorators like Components, Injectables, Directives, and more. I find myself frequently repeating a logic block that checks if a user is logged in and authorized to perform a specific function. Here's an example:
@Component()
class MyClass {
someMethod() {
if(this.authService.isLogged() && this.authService.isAuth(...)) {
// implementation
}
}
}
While this approach works, it can be quite cumbersome to read and not very intuitive for my colleagues. My goal is to create a decorator that first validates if a user is logged in, then checks their authorization status. If both conditions are met, the function should execute; otherwise, it should bypass execution and return a default value. Here's what I came up with for the login verification function:
export function isLogged() {
return (target, key, descriptor) {
const original = descriptor.value;
descriptor.value = function (...args: any[]) {
// <- implement login validation here
return original.apply(this, args);
};
return descriptor;
}
}
The challenge I'm currently facing is how to access the context services within the function to verify the user's login status without explicitly passing the 'this' keyword. To illustrate, this is the usage scenario I want to achieve:
@Component()
class MyClass {
@isAuth(...) // <- here without requiring 'this'
@isLogged()
someMethod() {
// implementation
}
}
I must stress that this decorator must rely on an authorization service for verification logic as it contains essential user login information and authorities required by the decorator. One possible solution to my query involves injecting services into designated functions. In the example decorator provided, there is a placeholder comment indicating where the call to the authorization service would fit in. While I believe there is a method to inject and invoke a service within a function, I haven't discovered any solutions online.