【问题标题】:class-transformer does not work : Transform function is not called类转换器不起作用:未调用转换函数
【发布时间】:2022-01-17 06:23:18
【问题描述】:

我尝试使用类转换器,但我做不到。 我也使用 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') 不是在我发出请求时调用,而是在服务器启动时调用一次。

谢谢!

【问题讨论】:

    标签: node.js typescript typegraphql class-transformer


    【解决方案1】:

    Typegoose 将类转换为 mongoose 模式和模型,除了 mongoose 提供的验证/转换之外,它不应用任何验证/转换,因此您的 class-transformer 装饰器只会在直接使用该类并使用其功能时被调用。 (如plainToClassclassToPlain

    在您的情况下,最好使用PropOptions get &amp; setpre-hooks

    作为说明,typegoose 提供了一个使用 class-transformer 与 typegoose 类 Integration Example: class-transformer 的指南,只是为了表明它可以像普通类一样使用。

    另外请注意,由于文档中提到的问题,目前建议不要使用class-transformer

    【讨论】:

    • 您好 hasezoey,非常感谢您的回答,但我正在尝试清理输入类型的电子邮件属性,我认为问题与 type-graphql 相关,而不是 typegoose。
    猜你喜欢
    • 2020-04-03
    • 2021-12-23
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    • 2016-08-24
    • 1970-01-01
    相关资源
    最近更新 更多