41 lines
1.3 KiB
TypeScript
41 lines
1.3 KiB
TypeScript
import { Injectable, NotFoundException } from '@nestjs/common';
|
|
import { InjectModel } from '@nestjs/mongoose';
|
|
import { Model } from 'mongoose';
|
|
import { User } from './entities/user.entity';
|
|
import { CreateUserDto } from './dto/create-user.dto';
|
|
import { UpdateUserDto } from './dto/update-user.dto';
|
|
|
|
@Injectable()
|
|
export class UsersService {
|
|
constructor(@InjectModel(User.name) private userModel: Model<User>) { }
|
|
|
|
async create(createUserDto: CreateUserDto) {
|
|
const createdUser = new this.userModel(createUserDto);
|
|
return createdUser.save();
|
|
}
|
|
|
|
async findAll() {
|
|
return this.userModel.find().exec();
|
|
}
|
|
|
|
async findOne(id: string) {
|
|
const user = await this.userModel.findById(id).exec();
|
|
if (!user) throw new NotFoundException(`User ${id} not found`);
|
|
return user;
|
|
}
|
|
|
|
async update(id: string, updateUserDto: UpdateUserDto) {
|
|
const updatedUser = await this.userModel
|
|
.findByIdAndUpdate(id, updateUserDto, { new: true })
|
|
.exec();
|
|
if (!updatedUser) throw new NotFoundException(`User ${id} not found`);
|
|
return updatedUser;
|
|
}
|
|
|
|
async remove(id: string):Promise<void> {
|
|
const result = await this.userModel.findByIdAndDelete(id).exec();
|
|
if (!result) throw new NotFoundException(`User ${id} not found`);
|
|
|
|
}
|
|
}
|