typescript decorators with arrow functions

835 views Asked by At

I necessarily need to implement arrow functions in this implementation and I need to convert the input from AWS into a custom model in order to avoid doing the same logic for each APIs. I thought of using decorators to do this each function. As it's considered as a property by the compiler it won't find the descriptor property and throw exceptions. Is there a workaround to trick the compiler to recognise the arrow function as an actual function and pass the descriptor?

 @API(EndpointType.POST)
  public login = async (event: Input): Promise<APIGatewayProxyResult> => {
     ... logic
  }

   export function API(apiType:EndpointType): any {
      return (target: any, propertyKey: string, descriptor?: TypedPropertyDescriptor<any>) => {
         descriptor.value = function(request) {
             ... logic
             const bindedOriginalFunction = originalFunction.bind(this)
             const result = bindedOriginalFunction(finalResult);
             return result
         }
       return descriptor;
   }
2

There are 2 answers

1
Luk Deathrage Prochzka On

Does it have to be an arrow function?

class Foo {
  async login(event: Input): Promise<APIGatewayProxyResult> { ... }
}

Arrow function in your case is not a method (function owned by the object). You have a property that hold a function (arrow function) that is owned someone else.

0
Luk Deathrage Prochzka On

Decorator is in fact just a function accepting funciton and returning function:

function API(endpoint) {
   return (target) => { 
      /*do stuff*/
   } 
}

So you can just do this

const undecorated = (someParams) => ...; 

const decorated = API(EdpointType.POST)(undecorated); 

It can be more streamliend to

const func = API(EndpointType.Post)((someParams) => ...);
 

You can do this even inside of a class

class Foo { 
   bar = API(EndpointType.POST)((someParams) => { 
       const someOtherPropertyAccess = this.property; 
       /* body of the function */
   });
}