crash-course-nest-js
Войти

crash-course-nest-js

crash-course-nest-js

Перейти на страницу: Проекты

Видео: Быстрый курс по Nest.js

  1. Добавим префикс в файле main.ts
    1
    app.setGlobalPrefix('api');
  2. Генерируем моудуль post
    1
    nest g mo post
  3. Генерируем контроллер post
    1
    nest g co post --no-spec
  4. Генерируем сервиса post
    1
    nest g s post --no-spec
  5. Генерируем dto post
    1
    nest g cl post/post.dto --no-spec
  6. Удалим файл app.controller.spec.ts, потому что он пока нам будет не нужен
    1
    ri src/app.controller.spec.ts

Работа с контроллером

  1. В контроллере создадим тестовые данные
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    posts: any[];
    
    constructor() {
     this.posts = [
       {
         id: 1,
         content: 'Тест 1',
         userName: 'Михаил',
       },
       {
         id: 2,
         content: 'Тест 2',
         userName: 'Макар',
       },
       {
         id: 3,
         content: 'Тест 3',
         userName: 'Джон',
       },
     ];
    }
  2. Получим все посты
    1
    2
    3
    4
    5
    // Получаем все посты
    @Get()
    async getAll() {
      return this.posts;
    }
  3. Создадим новый пост
    1
    2
    3
    4
    5
    // Создаем новый пост
    @Post()
    async create(@Body() dto: PostDto) {
      return [...this.posts, dto];
    }
  4. Получаем пост по id
    1
    2
    3
    4
    5
    // Получаем пост по id
    @Get(':id')
    async getById(@Param('id') id: string) {
      return this.posts.find((p) => p.id === Number(id));
    }
  5. Обновляем пост по id
    1
    2
    3
    4
    5
    6
    7
    // Обновление поста по id
    @Put(':id')
    async update(@Param('id') id: string, @Body() dto: CreatePostDto) {
     const post = await this.posts.find((p) => p.id === Number(dto.id));
     post.content = dto.content;
     return post;
    }
  6. Удаляем пост по id
    1
    2
    3
    4
    5
    // Удаление поста по id
    @Delete(':id')
    async delete(@Param('id') id: string) {
      return this.posts.filter((p) => p.id !== Number(id));
    }
Теги:
php