我有一个类Template
,其属性为_id
,具有来自class-transformer
和typed-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()
,则自定义装饰器将起作用。
答案 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),则它们的评估如下: