class-transformer does not work : Transform function is not called

Viewed 1654

I try to use class-transformer but i can't do it. I also use type-graphql and @typegoose/typegoose Here's my code:

My Decorator

import { Transform } from 'class-transformer';

export function Trim() {
  console.log('DECORATOR');

  return Transform(({ value }: { value: string }) => {
    console.log('value: ', value);
    return value.trim();
  });
}

My InputType

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

My Resolver

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

My Entity

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

My Request

POST http://localhost:5000/app HTTP/1.1
Content-Type: application/json
X-REQUEST-TYPE: GraphQL

mutation 
{
   createAccount (data : {
       email: "   email@gmail.com    ",
   })
}

The problem is that the console.log('value: ', value) inside Transform function is never call and my email is not trim.

Also console.log('DECORATOR') is not call when I do the request but just one time when server starting.

Thanks !

1 Answers

Typegoose transpiles classes into mongoose schemas & models, it does not apply any validation / transformation aside from mongoose provided ones, so your class-transformer decorators would only be called when using the class directly and using its functions. (like plainToClass and classToPlain)

In your case, it would be better to either use PropOptions get & set or pre-hooks.

As a note, typegoose provides a guide for using class-transformer with typegoose classes Integration Example: class-transformer, just to show that it can be used like normal classes.

Also note, it is currently recommended against using class-transformer because of mentioned issues inside the documentation.

Related