如何在Typescript中组合多个属性装饰器?

时间:2018-08-22 14:46:56

标签: typescript decorator

我有一个类Template,其属性为_id,具有来自class-transformertyped-graphql的修饰符

import {classToPlain, Exclude, Expose, plainToClass, Type } from 'class-transformer';
import { ExposeToGraphQL } from '../../decorators/exposeToGraphQL';
import { Field, ID, MiddlewareInterface, NextFn, ObjectType, ResolverData } from 'type-graphql';
import { getClassForDocument, InstanceType, prop, Typegoose } from 'typegoose';
/**
  * Class
  * @extends Typegoose
  */
@Exclude()
@ObjectType()
class Template extends Typegoose {
  // @Expose and @Type should be both covered by ExposeToGraphQL
  // @Expose()
  @Type(() => String)
  @ExposeToGraphQL()
  @Field(() => ID)
  public _id?: mongoose.Types.ObjectId;
}

现在,我尝试将两者结合成一个新的自定义属性装饰器:

/**
 *
 */
import { Expose } from 'class-transformer';
import 'reflect-metadata';

const formatMetadataKey: Symbol = Symbol('ExposeToGraphQL');

function ExposeToGraphQL() {
  console.log('ExposeToGraphQL');

  return Expose();
}

function getExposeToGraphQL(target: any, propertyKey: string) {
  console.log('getExposeToGraphQL');

  return Reflect.getMetadata(formatMetadataKey, target, propertyKey);
}

export {
  ExposeToGraphQL,
  getExposeToGraphQL,
};

如果我仅返回Expose()的结果,但是我不知道如何在@Expose中组合@Type@ExposeToGraphQL(),则自定义装饰器将起作用。

1 个答案:

答案 0 :(得分:3)

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);
  }
}

然后您可以按以下方式使用该装饰器:

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

您可以找到装饰器in this link的官方文档。

@Expose@Type()基本上是Decorator Factories。装饰厂的主要目的:

  • 它返回一个函数
  • 该函数将在运行时(在类(在本例中为Template定义之后)带有两个参数的情况下被调用:
    • 类原型(Template.prototype
    • 装饰器附加到的属性的名称(_id

如果将两个或多个装饰器附加到同一属性(称为Decorator Composition),则它们的评估如下:

  • 工厂函数的执行顺序与用代码编写的顺序相同
  • 工厂功能返回的功能以颠倒的顺序执行
相关问题