Copy @ Module ({
imports : [ TypeOrmModule .forFeature ([User])] ,
controllers : [UsersController] ,
providers : [UsersService] ,
})
export class UsersModule {}
Copy @ Controller ( 'users' )
export class UsersController {
constructor ( private readonly usersService : UsersService ) {}
@ Post ()
create (@ Body () createUserDto : CreateUserDto ) {
return this . usersService .create (createUserDto);
}
@ Get ()
findAll () {
return this . usersService .findAll ();
}
@ Get ( ':id' )
findOne (@ Param () { id } : IdDto ) {
return this . usersService .findOne (id);
}
@ Patch ( ':id' )
update (@ Param () { id } : IdDto , @ Body () updateUserDto : UpdateUserDto ) {
return this . usersService .update (id , updateUserDto);
}
@ Delete ( ':id' )
remove (@ Param () { id } : IdDto ) {
return this . usersService .remove (id);
}
}
Copy @ Injectable ()
export class UsersService {
constructor (
@ InjectRepository (User)
private readonly usersRepository : Repository < User > ,
) {}
create (createUserDto : CreateUserDto ) {
const user = this . usersRepository .create (createUserDto);
return this . usersRepository .save (user);
}
findAll () {
return this . usersRepository .find ();
}
async findOne (id : number ) {
return this . usersRepository .findOneByOrFail ({ id });
}
async update (id : number , updateUserDto : UpdateUserDto ) {
const user = await this . usersRepository .preload ({
id ,
... updateUserDto ,
});
if ( ! user) {
throw new NotFoundException ( 'User not found' );
}
return this . usersRepository .save (user);
}
async remove (id : number ) {
const user = await this .findOne (id);
return this . usersRepository .remove (user);
}
}
We do this to be more straightforward in our studies. But don't worry, this will not be committed. At the end of this module, this will be stashed .