#Is fixed @UseInterceptors(ClassSerializerInterceptor) problem in Nest.js 10.1.17

34 messages · Page 1 of 1 (latest)

viscid lagoon
#

I am using Nest version 10.1.17. But It's not working correctly. So I want to know about this.

north ore
#

How is it not working?

viscid lagoon
#
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument, ObjectId, Types } from 'mongoose';
import { Exclude, Type, Transform } from 'class-transformer';
import { Role } from './role.schema';
import { BaseSchema } from './base.schema';

export type UserDocument = HydratedDocument<User>;

@Schema()
export class User extends BaseSchema {
  @Transform(({ value }) => value.toString())
  @Type(() => String)
  _id: ObjectId;

  @Prop()
  code: string;

  @Prop({ required: true })
  first_name: string;

  @Prop({ required: true })
  last_name: string;

  @Prop({ required: true, unique: true })
  email: string;

  @Prop({ required: true })
  @Exclude()
  password: string;

  @Prop({ type: [{ type: Types.ObjectId, ref: Role.name }] })
  roles: Role[];
}

export const UserSchema = SchemaFactory.createForClass(User);

But password is not disappeared.

north ore
#

Are you returning an instance of the User class or just what mongo returns?

viscid lagoon
#

user.controller.ts

@UseInterceptors(ClassSerializerInterceptor)
  @Get('users')
  //@UseGuards(AuthGuard)
  async getUsers(): Promise<User[]> {
    return await this.userAuthService.getUsers();
  }

user.service.ts

async getUsers(params: Record<string, unknown> = {}): Promise<User[]> {
    try {
      const users = await this.userRepository.find(params, 'roles');
      if (!users) {
        throw new NotFoundException('User not found');
      }
      return users;
    } catch (error) {
      if (error instanceof NotFoundException) {
        throw error;
      }
      throw new Error('An error occurred while retrieving users');
    }
  }

user.repository.ts

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { FilterQuery, Model } from 'mongoose';
import { BaseRepository } from 'src/common/repositories/base.repository';
import { User, UserDocument } from 'src/schemas/user.schema';

@Injectable()
export class UserRepository extends BaseRepository<UserDocument> {
  constructor(@InjectModel(User.name) userModel: Model<UserDocument>) {
    super(userModel);
  }
}

base.repository.ts

import {
  AggregateOptions,
  Document,
  FilterQuery,
  Model,
  PipelineStage,
  UpdateQuery,
} from 'mongoose';

export abstract class BaseRepository<T extends Document> {
  constructor(protected readonly entityModel: Model<T>) {}

  async find(
    entityFilter: FilterQuery<T>,
    populateField?: string,
    projection?: Record<string, unknown>,
    options?: Record<string, unknown>,
  ): Promise<T[]> {
    return this.entityModel
      .find(entityFilter, { ...projection }, options)
      .populate(populateField);
  }
north ore
#

That does not return instances of the class, just objects that look like the class type wise

viscid lagoon
#

If so, how can I return instances of the class.

north ore
#

Well. How do you create instances?

viscid lagoon
#

Where is the issues in my codes?

viscid lagoon
north ore
#

You use the new keyword and constructor, right?

viscid lagoon
#

You mean in repository?

north ore
#

Whatever you want before you return from the controller

viscid lagoon
#

I am not understand, because I am a newbie. So could you let me know in my codes?

#

Sorry

north ore
#

What do you not understand?

viscid lagoon
#

You mean I have to create the instance of User schema using new and constructor in User schema>

north ore
#

I mean, before you return from the controller, you need to return an instance of the User class

viscid lagoon
#

for example, like this?

export class User {
  id: string;
  username: string;
  email: string;

  constructor(id: string, username: string, email: string) {
    this.id = id;
    this.username = username;
    this.email = email;
  }
}
import { Controller, Get, Param } from '@nestjs/common';
import { UserService } from './user.service';
import { User } from './user.model'; // Import your User class

@Controller('users')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get(':id')
  async getUser(@Param('id') id: string): Promise<User> {
    // Retrieve user data from your service or database
    const userData = await this.userService.getUserById(id);

    // Create an instance of the User class and populate it with data
    const user = new User(userData.id, userData.username, userData.email);

    // Return the user instance
    return user;
  }
}
north ore
#

Yep

viscid lagoon
#

Okay, thanks. I'll try.

viscid lagoon
#

Hi, are you still here?

#

Can you let me know the best and latest boilerplate project?

#

All features are available

north ore
viscid lagoon
#

I mean I want to get the best boilerplate using the latest version of Nest. So I can start from scratch.

#

Because right now I am using the project built by me. So I can't use all features of Nest.

north ore
#

You want a "boilerplate" so you can "start from scratch"?

So I can't use all features of Nest.
Why not?

viscid lagoon
#

I tried to fix it so far, but no result yet.

#

So I think I will start with your recommened boilerplate from scratch again.

north ore
#

I don't recommend a boilerplate. I use nest new or @nx/nest:app if in an Nx monorepo, and build up from there

viscid lagoon
#

If so, can you show me your sample work which available to work it : @UseInterceptors(ClassSerializerInterceptor)?

north ore
#

I also don't use the ClassSerializerInterceptor because I don't use class-transformer or class-valdiator. I've been using valibot with my @nest-lab/typeschema package.

#

If you want to make a minimum reproduction, I'll look into why it isn't working for you