In our project we have some wrapper functions for apollo graphql resolvers for authentication and other checks that shall be performed before the resolver is executed.
Now I'd like to shift from wrapper functions to typescript decorators.
I found lots of examples on how to use decorators on functions or classes
@decorator
function fn() {}
@clsDecorator
class Cls {
@methodDecorator
public myMethod() {}
}
Unfortunatly, our codebase collects resolvers from several application modules defined as properties in a plain javascript object. When I try to use a decorator on properties inside the object, I get errors from typescript-eslint like Property assignment expected
or Declaration expected
and the decorators aren't applied to the function.
Is there any way to use decorators in a case like this?
export const ModuleResolvers = {
Query: {
// doesnt work
@decorator
queryResolver1(obj, args, context) {}
// doesnt work
@decorator
queryResolver2: (obj, args, context) => {}
}
}
A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter.
so yes. you can't attach decorators in object's property, Since it isn't included in range of typescript's decorator support.
For same reason, in your example above, This code won't works also:
@decorator
function fn() {}
If you really want to do this, then you can use static
keyword in typescript, by using class like namespace.
export const ModuleObject = {
@first()
testMethod: () => {} // This won't work
}
export class ModuleNamespaceClass {
@first()
static testMethod() {} // But this will works well, because this method is in "class" scope
}
// Use it like this...
ModuleNamespaceClass.testMethod();
if you need more info, check Typescript document - Decorator.