Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable, Controller, Post, Body, Get, Param, UseGuards, BadRequestException, NotFoundException, UnauthorizedException, Module } from '@nestjs/common';
- import { InjectRepository } from '@nestjs/typeorm';
- import { Repository, Entity, Column, PrimaryGeneratedColumn, ManyToOne } from 'typeorm';
- import { ApiTags, ApiBearerAuth } from '@nestjs/swagger';
- import { JwtService } from '@nestjs/jwt';
- import { AuthGuard } from '@nestjs/passport';
- import { validate } from 'class-validator';
- import * as bcrypt from 'bcrypt';
- import { IsString, IsEmail, MinLength, IsNumber, IsPositive } from 'class-validator';
- import { InjectQueue } from '@nestjs/bull';
- import { Queue } from 'bull';
- @Entity()
- export class User {
- @PrimaryGeneratedColumn()
- id: number;
- @Column()
- @IsString()
- name: string;
- @Column({ unique: true })
- @IsEmail()
- email: string;
- @Column()
- @IsString()
- @MinLength(8)
- password: string;
- }
- @Entity()
- export class Order {
- @PrimaryGeneratedColumn()
- id: number;
- @ManyToOne(() => User, (user) => user.id)
- user: User;
- @Column()
- @IsNumber()
- @IsPositive()
- totalPrice: number;
- @Column({ default: 'pending' })
- status: string;
- }
- export class CreateOrderDto {
- @IsNumber()
- @IsPositive()
- totalPrice: number;
- }
- @Injectable()
- export class OrderService {
- private readonly saltRounds = 10;
- constructor(
- @InjectRepository(User)
- private readonly userRepository: Repository<User>,
- @InjectRepository(Order)
- private readonly orderRepository: Repository<Order>,
- private readonly jwtService: JwtService,
- @InjectQueue('notifications')
- private readonly notificationQueue: Queue,
- ) {}
- async register(name: string, email: string, password: string): Promise<{ accessToken: string }> {
- const existingUser = await this.userRepository.findOne({ where: { email } });
- if (existingUser) {
- throw new BadRequestException('Email уже занят');
- }
- const hashedPassword = await bcrypt.hash(password, this.saltRounds);
- const user = this.userRepository.create({ name, email, password: hashedPassword });
- await this.userRepository.save(user);
- const payload = { sub: user.id, email: user.email };
- return { accessToken: this.jwtService.sign(payload) };
- }
- async createOrder(userId: number, createOrderDto: CreateOrderDto): Promise<Order> {
- const user = await this.userRepository.findOne({ where: { id: userId } });
- if (!user) {
- throw new NotFoundException('Пользователь не найден');
- }
- const errors = await validate(createOrderDto);
- if (errors.length > 0) {
- throw new BadRequestException('Некорректные данные заказа');
- }
- let { totalPrice } = createOrderDto;
- if (totalPrice > 1000) {
- totalPrice *= 0.9; // скидка
- }
- const order = this.orderRepository.create({ user, totalPrice, status: 'pending' });
- await this.orderRepository.save(order);
- await this.notificationQueue.add('sendOrderConfirmation', {
- userId: user.id,
- orderId: order.id,
- email: user.email,
- });
- return order;
- }
- async getOrderStatus(orderId: number): Promise<string> {
- const order = await this.orderRepository.findOne({ where: { id: orderId } });
- if (!order) {
- throw new NotFoundException('Заказ не найден');
- }
- return order.status;
- }
- async updateOrderStatus(orderId: number, status: string): Promise<void> {
- const order = await this.orderRepository.findOne({ where: { id: orderId } });
- if (!order) {
- throw new NotFoundException('Заказ не найден');
- }
- order.status = status;
- await this.orderRepository.save(order);
- if (status === 'completed') {
- await this.notificationQueue.add('sendOrderCompleted', {
- orderId: order.id,
- email: order.user.email,
- });
- }
- }
- }
- @ApiTags('orders')
- @Controller('orders')
- export class OrderController {
- constructor(private readonly orderService: OrderService) {}
- @Post('register')
- async register(@Body() body: { name: string; email: string; password: string }) {
- return this.orderService.register(body.name, body.email, body.password);
- }
- @Post()
- @UseGuards(AuthGuard('jwt'))
- @ApiBearerAuth()
- async createOrder(@Body() createOrderDto: CreateOrderDto, @Param('userId') userId: number) {
- return this.orderService.createOrder(userId, createOrderDto);
- }
- @Get(':orderId/status')
- @UseGuards(AuthGuard('jwt'))
- @ApiBearerAuth()
- async getOrderStatus(@Param('orderId') orderId: string) {
- return this.orderService.getOrderStatus(+orderId);
- }
- @Post(':orderId/status')
- @UseGuards(AuthGuard('jwt'))
- @ApiBearerAuth()
- async updateOrderStatus(@Param('orderId') orderId: string, @Body('status') status: string) {
- await this.orderService.updateOrderStatus(+orderId, status);
- return { message: 'Статус обновлен' };
- }
- }
- @Module({
- providers: [OrderService],
- controllers: [OrderController],
- })
- export class AppModule {}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement