apps/api: add /update method

This commit is contained in:
vchikalkin 2024-01-11 13:39:57 +03:00
parent b28c5a4f3f
commit 2f3f0183e5
2 changed files with 31 additions and 1 deletions

View File

@ -10,6 +10,7 @@ import {
Get,
HttpException,
HttpStatus,
Patch,
Post,
Query,
Req,
@ -68,6 +69,21 @@ export class AccountController {
return this.accountService.delete(username);
}
@Patch('/update')
@ApiResponse({
status: HttpStatus.OK,
type: Account,
})
async update(@Body() createAccountDto: CreateAccountDto, @Res() reply: FastifyReply) {
try {
const updatedAccount = await this.accountService.update(createAccountDto);
return reply.status(HttpStatus.OK).send(updatedAccount);
} catch (error) {
throw new HttpException(error, HttpStatus.BAD_REQUEST);
}
}
@Post('/login')
async login(@Body() credentials: Credentials, @Res() reply: FastifyReply) {
try {

View File

@ -1,5 +1,5 @@
import type { CreateAccountDto } from './dto/create-account.dto';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectModel } from '@nestjs/mongoose';
import * as bcrypt from 'bcrypt';
@ -18,6 +18,11 @@ export class AccountService {
) {}
public async create(createAccountDto: CreateAccountDto): Promise<Account> {
Object.keys(createAccountDto).forEach((field) => {
if (['_id', '__v'].includes(field))
throw new BadRequestException(`Prop ${field} is not allowed`);
});
const password = createAccountDto.password || generatePassword();
const createdAccount = new this.accountModel({ ...createAccountDto, password });
@ -35,6 +40,15 @@ export class AccountService {
return this.accountModel.findOneAndDelete({ username }).exec();
}
public async update({ username, ...props }: CreateAccountDto): Promise<Account> {
Object.keys(props).forEach((field) => {
if (['_id', '__v', 'password'].includes(field))
throw new BadRequestException(`Prop ${field} is not allowed`);
});
return this.accountModel.findOneAndUpdate({ username }, props).exec();
}
public async login({ login, password }: Credentials) {
try {
const account = await this.accountModel.findOne({ username: login });