use*_*995 6 decorator typescript
我有一个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;
}
Run Code Online (Sandbox Code Playgroud)
现在,我尝试将两者结合成一个新的自定义属性装饰器:
/**
*
*/
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,
};
Run Code Online (Sandbox Code Playgroud)
该定制的装饰作品,如果我只返回的结果Expose(),但我不知道如何结合@Expose和@Type在@ExposeToGraphQL()。
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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以按如下方式使用该装饰器:
class Template extends Typegoose {
@ExposeToGraphQL(/*exposeOptions*/ undefined, /*typeFunction*/ () => String)
@Field(() => ID)
public _id?: mongoose.Types.ObjectId;
}
Run Code Online (Sandbox Code Playgroud)
您可以在此链接中找到装饰器的官方文档。
@Expose并且@Type()基本上是装饰工厂。装饰厂的主要目的:
Template,已定义)被调用,并带有2个参数:
Template.prototype)_id)的属性的名称。如果将两个或多个装饰器附加到同一属性(称为Decorator Composition),则按以下方式评估它们: