nest_typeorm
Войти

Project - nest_typeorm

Project - nest_typeorm

Шаг 1 - Установка NestJS

  1. Установка NestJS ClI
    1
    yarn add @nestjs/cli
  2. Создадим новое приложение NestJS
    1
    nest n .
    или
    1
    nest n <наименование_приложения>
  3. Установим swagger для формирования документации по API
    1
    $ yarn add @nestjs/swagger
  4. main.ts

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    import { NestFactory } from '@nestjs/core';
    import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
    import { AppModule } from './app.module';
    
    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
    
      const config = new DocumentBuilder()
        .setTitle('Cats example')
        .setDescription('The cats API description')
        .setVersion('1.0')
        .addTag('cats')
        .build();
      const document = SwaggerModule.createDocument(app, config);
      SwaggerModule.setup('api', app, document);
    
      await app.listen(3000);
    }
    bootstrap();


  1. Генерация модуля
    1
    nest g mo <наименование_модуля>
  2. Создание контроллера
    1
    nest g co <наименование_контроллера> --no-spec
  3. Создание сервиса
    1
    nest g s <наименование_контроллера> --no-spec
  4. Создание DTO
    1
    nest g cl <name>/dto/<name>.dto --no-spec
  • Отключение spec создание spec файлов
    1
    --no-spec
  • 1
    app.setGlobalPrefix('api');


  • app.controller.ts

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    import { Body, Controller, Get, Param, Post, Put } from '@nestjs/common';
    import { ClientsDto } from './dto/create-clients.dto';
    import { UpdateClientsDto } from './dto/update-clients.dto';
    
    @Controller('clients')
    export class ClientsController {
      clients: any[];
    
      constructor() {
        this.clients = [
          {
            id: 1,
            name: 'Client1',
          },
          {
            id: 2,
            name: 'Client2',
          },
        ];
      }
    
      @Get()
      async getAll() {
        return this.clients;
      }
    
      @Post()
      async create(@Body() dto: ClientsDto) {
        return [...this.clients, dto];
      }
    
      @Get(':id')
      async getById(@Param('id') id: number) {
        return this.clients.find((c) => c.id === Number(id));
      }
    
      @Put(':id')
      async update(@Body() dto: UpdateClientsDto){
        const clients = await this.clients.find((c) => c.id === Number(dto.id))
        return clients
      }
    }
    Теги:
    php