Создание API для добавления и просмотра записей из модели Documents на NestJS

Вот пошаговое руководство для создания REST API на NestJS, которое позволяет добавлять и просматривать записи из модели Documents.


1. Установка и настройка проекта NestJS

Если у вас еще нет проекта NestJS, создайте его:

bash

npm i -g @nestjs/cli
nest new documents-api

Установите Prisma и необходимые зависимости:

bash

npm install @prisma/client
npm install prisma --save-dev

Инициализируйте Prisma:

bash

npx prisma init

Настройте файл prisma/schema.prisma с вашей моделью Documents и другими связанными моделями.


2. Генерация модуля, контроллера и сервиса

Сгенерируйте модуль, контроллер и сервис для работы с моделью Documents:

bash

nest g module documents
nest g controller documents
nest g service documents


3. Настройка PrismaService

Создайте файл prisma.service.ts в папке src для работы с Prisma:

typescript

import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
  async onModuleInit() {
    await this.$connect();
  }

  async onModuleDestroy() {
    await this.$disconnect();
  }
}

Зарегистрируйте PrismaService в AppModule:

typescript

import { Module } from '@nestjs/common';
import { PrismaService } from './prisma.service';

@Module({
  providers: [PrismaService],
  exports: [PrismaService],
})
export class AppModule {}


4. Реализация сервиса DocumentsService

В файле documents.service.ts реализуйте методы для добавления и получения записей:

typescript

import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma.service';
import { Documents } from '@prisma/client';

@Injectable()
export class DocumentsService {
  constructor(private prisma: PrismaService) {}

  async createDocument(data: { documentNumber: string; documentDate: Date; title: string; filepath: string; folderId?: number; documentTypeId?: number }): Promise<Documents> {
    return this.prisma.documents.create({
      data,
    });
  }

  async getAllDocuments(): Promise<Documents[]> {
    return this.prisma.documents.findMany();
  }
}


5. Реализация контроллера DocumentsController

В файле documents.controller.ts настройте маршруты для добавления и получения записей:

typescript

import { Body, Controller, Get, Post } from '@nestjs/common';
import { DocumentsService } from './documents.service';

@Controller('documents')
export class DocumentsController {
  constructor(private readonly documentsService: DocumentsService) {}

  @Post()
  async createDocument(@Body() body: { documentNumber: string; documentDate: Date; title: string; filepath: string; folderId?: number; documentTypeId?: number }) {
    return this.documentsService.createDocument(body);
  }

  @Get()
  async getAllDocuments() {
    return this.documentsService.getAllDocuments();
  }
}


6. Настройка маршрутов

Убедитесь, что модуль DocumentsModule зарегистрирован в AppModule:

typescript

import { Module } from '@nestjs/common';
import { DocumentsModule } from './documents/documents.module';
import { PrismaService }#### Создание API для модели Documents в NestJS

Для создания API для модели `Documents` в NestJS, мы выполним следующие шаги:

1. **Создание контроллера**:
   Контроллер будет обрабатывать входящие HTTP-запросы и взаимодействовать с сервисом для выполнения CRUD-операций.

   ```typescript
   import { Body, Controller, Get, Param, Post } from '@nestjs/common';
   import { DocumentsService } from './documents.service';
   import { CreateDocumentDto } from './dto/create-document.dto';

   @Controller('documents')
   export class DocumentsController {
     constructor(private readonly documentsService: DocumentsService) {}

     @Get()
     async findAll() {
       return this.documentsService.findAll();
     }

     @Get(':id')
     async findOne(@Param('id') id: number) {
       return this.documentsService.findOne(id);
     }

     @Post()
     async create(@Body() createDocumentDto: CreateDocumentDto) {
       return this.documentsService.create(createDocumentDto);
     }
   }

  1. Создание сервиса: Сервис будет содержать логику для взаимодействия с базой данных через Prisma.typescriptimport { Injectable } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { CreateDocumentDto } from './dto/create-document.dto'; @Injectable() export class DocumentsService { constructor(private prisma: PrismaService) {} async findAll() { return this.prisma.documents.findMany(); } async findOne(id: number) { return this.prisma.documents.findUnique({ where: { id } }); } async create(createDocumentDto: CreateDocumentDto) { return this.prisma.documents.create({ data: createDocumentDto }); } }
  2. Создание DTO (Data Transfer Object): DTO определяет структуру данных, которые будут передаваться в запросах.typescriptimport { IsDate, IsNotEmpty, IsString } from 'class-validator'; export class CreateDocumentDto { @IsNotEmpty() @IsString() documentNumber: string; @IsNotEmpty() @IsDate() documentDate: Date; @IsNotEmpty() @IsString() title: string; @IsNotEmpty() @IsString() filepath: string; folderId?: number; documentTypeId?: number; }
  3. Регистрация модуля в приложении: Добавьте модуль DocumentsModule в app.module.ts.typescriptimport { Module } from '@nestjs/common'; import { DocumentsModule } from './documents/documents.module'; @Module({ imports: [DocumentsModule], }) export class AppModule {}
  4. Реализация маршрутов: Определите маршруты для взаимодействия с моделью Documents в documents.module.ts.typescriptimport { Module } from '@nestjs/common'; import { DocumentsController } from './documents.controller'; import { DocumentsService } from './documents.service'; import { PrismaService } from '../prisma/prisma.service'; @Module({ controllers: [DocumentsController], providers: [DocumentsService, PrismaService], }) export class DocumentsModule {}

Теперь вы можете использовать следующие маршруты для взаимодействия с моделью Documents:

  • GET /documents: Получение списка всех документов
  • GET /documents/:id: Получение документа по ID
  • POST /documents: Создание нового документа

Примеры использования:

javascript

GET /documents

Ответ:

json

[
  {
    "id": 1,
    "documentNumber": "DOC-1",
    "documentDate": "2023-04-01T00:00:00.000Z",
    "title": "Document Title 1",
    "filepath": "/path/to/document_1.pdf",
    "folderId": 1,
    "documentTypeId": 1
  },
  {
    "id": 2,
    "documentNumber": "DOC-2",
    "documentDate": "2023-04-02T00:00:00.000Z",
    "title": "Document Title 2",
    "filepath": "/path/to/document_2.pdf",
    "folderId": 2,
    "documentTypeId": 2
  },
  // ...
]

javascript

POST /documents
{
  "documentNumber": "DOC-11",
  "documentDate": "2023-04-11T00:00:00.000Z",
  "title": "New Document",
  "filepath": "/path/to/document_11.pdf",
  "folderId": 3,
  "documentTypeId": 4
}

Ответ:

json

{
  "id": 11,
  "documentNumber": "DOC-11",
  "documentDate": "2023-04-11T00:00:00.000Z",
  "title": "New Document",
  "filepath": "/path/to/document_11.pdf",
  "folderId": 3,
  "documentTypeId": 4
}

Это базовое API для модели Documents. Вы можете расширить его, добавив дополнительные операции, такие как обновление и удаление документов.