#Is fixed @UseInterceptors(ClassSerializerInterceptor) problem in Nest.js 10.1.17
34 messages · Page 1 of 1 (latest)
How is it not working?
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.
Are you returning an instance of the User class or just what mongo returns?
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);
}
That does not return instances of the class, just objects that look like the class type wise
If so, how can I return instances of the class.
Well. How do you create instances?
Where is the issues in my codes?
Yes,
You use the new keyword and constructor, right?
You mean in repository?
Whatever you want before you return from the controller
I am not understand, because I am a newbie. So could you let me know in my codes?
Sorry
What do you not understand?
You mean I have to create the instance of User schema using new and constructor in User schema>
I mean, before you return from the controller, you need to return an instance of the User class
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;
}
}
Yep
Okay, thanks. I'll try.
Hi, are you still here?
Can you let me know the best and latest boilerplate project?
All features are available
What do you mean by this?
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.
You want a "boilerplate" so you can "start from scratch"?
So I can't use all features of Nest.
Why not?
I tried to fix it so far, but no result yet.
So I think I will start with your recommened boilerplate from scratch again.
I don't recommend a boilerplate. I use nest new or @nx/nest:app if in an Nx monorepo, and build up from there
If so, can you show me your sample work which available to work it : @UseInterceptors(ClassSerializerInterceptor)?