我尝试使用类转换器,但我做不到。我还使用 type-graphql 和 @typegoose/typegoose 这是我的代码:
我的装饰器
import { Transform } from 'class-transformer';
export function Trim() {
console.log('DECORATOR');
return Transform(({ value }: { value: string }) => {
console.log('value: ', value);
return value.trim();
});
}
我的输入类型
import { IsEmail } from 'class-validator';
import { InputType, Field } from 'type-graphql';
import { User } from '../Entities/User';
import { Trim } from '../../Decorators/Sanitize';
@InputType({ description: 'Input for user creation' })
export class AddUserInput implements Partial<User> {
@Field()
@Trim()
@IsEmail({ domain_specific_validation: true, allow_utf8_local_part: false })
email!: string;
}
我的解析器
import { Arg, Mutation, Resolver } from 'type-graphql';
import { User } from '../Entities/User';
import { AddUserInput } from '../Types/UsersInputs';
@Resolver(() => User)
export class UserResolvers {
@Mutation(() => String, { description: 'Register an admin' })
async createAccount(@Arg('data') data: AddUserInput): Promise<string> {
console.log({ ...data });
return data.email;
}
}
我的实体
import { prop, getModelForClass } from '@typegoose/typegoose';
import { ObjectType, Field } from 'type-graphql';
@ObjectType({ description: 'User model' })
export class User {
@Field({ description: 'The user email' })
@prop({ required: true, unique: true, match: [/\S+@\S+\.\S+/, 'is invalid'] })
email!: string;
}
export const UserModel = getModelForClass(User, {
schemaOptions: { timestamps: true }
});
我的请求
POST http://localhost:5000/app HTTP/1.1
Content-Type: application/json
X-REQUEST-TYPE: GraphQL
mutation
{
createAccount (data : {
email: " email@gmail.com ",
})
}
问题是console.log('value: ', value)
内部的 Transform 函数永远不会被调用,我的电子邮件也没有被修剪。
console.log('DECORATOR')
当我发出请求时也不会调用,而只是在服务器启动时调用一次。
谢谢 !