How to combine multiple property decorators in Typescript?

后端 未结 1 1674
我寻月下人不归
我寻月下人不归 2021-01-02 03:47

I have a class Template with a property _id which has decorators from class-transformer and typed-graphql



        
相关标签:
1条回答
  • 2021-01-02 04:41
    import { Expose, Type, TypeOptions, ExposeOptions } from 'class-transformer';
    
    /**
     * Combines @Expose then @Types decorators.
     * @param exposeOptions options that passes to @Expose()
     * @param typeFunction options that passes to @Type()
     */
    function ExposeToGraphQL(exposeOptions?: ExposeOptions, typeFunction?: (type?: TypeOptions) => Function) {
      const exposeFn = Expose(exposeOptions);
      const typeFn = Type(typeFunction);
    
      return function (target: any, key: string) {
        typeFn(target, key);
        exposeFn(target, key);
      }
    }
    

    Then you can use that decorator as follow:

    class Template extends Typegoose {
        @ExposeToGraphQL(/*exposeOptions*/ undefined, /*typeFunction*/ () => String)
        @Field(() => ID)
        public _id?: mongoose.Types.ObjectId;
    }
    

    You can find official documentation for decorator in this link.

    @Expose and @Type() are basically Decorator Factories. The main purpose of a decorator factory:

    • it return a function
    • that function will be called at runtime (right after the class, in this case is Template, was defined) with 2 arguments:
      • class prototype (Template.prototype)
      • name of the property which the decorator attached to (_id).

    If two or more decorators are attached to a same property (called as Decorator Composition), they are evaluated as follow:

    • The factory functions are executed in the same order as they are written in code
    • The functions returned by factory functions are executed in reversed order
    0 讨论(0)
提交回复
热议问题