From 94f9b0652746838a007736c6b092b9730bfa24df Mon Sep 17 00:00:00 2001 From: Arswarog Date: Mon, 26 Oct 2026 17:16:13 +0300 Subject: [PATCH] =?UTF-8?q?api:=20=D0=BF=D1=80=D0=B8=D0=BB=D0=BE=D0=B6?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20NestJS=20=D0=B8=20e2e-=D1=82=D0=B5?= =?UTF-8?q?=D1=81=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Каркас api: NestJS со сборкой через webpack, health-контроллер с версией и статусом БД, Dockerfile, тесты Vitest и e2e-тесты на Jest. --- apps/api-e2e/.spec.swcrc | 22 +++ apps/api-e2e/eslint.config.mjs | 3 + apps/api-e2e/jest.config.cts | 21 ++ apps/api-e2e/package.json | 5 + apps/api-e2e/project.json | 53 +++++ apps/api-e2e/src/api/api.spec.ts | 11 ++ apps/api-e2e/src/support/global-setup.ts | 16 ++ apps/api-e2e/src/support/global-teardown.ts | 9 + apps/api-e2e/src/support/test-setup.ts | 8 + apps/api-e2e/tsconfig.json | 14 ++ apps/api/Dockerfile | 25 +++ apps/api/deny-external-plugin.js | 96 ++++++++++ apps/api/eslint.config.mjs | 3 + apps/api/package.json | 18 ++ apps/api/project.json | 202 ++++++++++++++++++++ apps/api/src/app/app.controller.ts | 12 ++ apps/api/src/app/app.module.ts | 10 + apps/api/src/app/app.service.ts | 8 + apps/api/src/health/health.controller.ts | 47 +++++ apps/api/src/main.ts | 46 +++++ apps/api/src/test-setup.ts | 1 + apps/api/tsconfig.app.json | 24 +++ apps/api/tsconfig.json | 13 ++ apps/api/tsconfig.spec.json | 16 ++ apps/api/vitest.config.ts | 35 ++++ apps/api/webpack.base.js | 51 +++++ apps/api/webpack.config.js | 22 +++ 27 files changed, 791 insertions(+) create mode 100644 apps/api-e2e/.spec.swcrc create mode 100644 apps/api-e2e/eslint.config.mjs create mode 100644 apps/api-e2e/jest.config.cts create mode 100644 apps/api-e2e/package.json create mode 100644 apps/api-e2e/project.json create mode 100644 apps/api-e2e/src/api/api.spec.ts create mode 100644 apps/api-e2e/src/support/global-setup.ts create mode 100644 apps/api-e2e/src/support/global-teardown.ts create mode 100644 apps/api-e2e/src/support/test-setup.ts create mode 100644 apps/api-e2e/tsconfig.json create mode 100644 apps/api/Dockerfile create mode 100644 apps/api/deny-external-plugin.js create mode 100644 apps/api/eslint.config.mjs create mode 100644 apps/api/package.json create mode 100644 apps/api/project.json create mode 100644 apps/api/src/app/app.controller.ts create mode 100644 apps/api/src/app/app.module.ts create mode 100644 apps/api/src/app/app.service.ts create mode 100644 apps/api/src/health/health.controller.ts create mode 100644 apps/api/src/main.ts create mode 100644 apps/api/src/test-setup.ts create mode 100644 apps/api/tsconfig.app.json create mode 100644 apps/api/tsconfig.json create mode 100644 apps/api/tsconfig.spec.json create mode 100644 apps/api/vitest.config.ts create mode 100644 apps/api/webpack.base.js create mode 100644 apps/api/webpack.config.js diff --git a/apps/api-e2e/.spec.swcrc b/apps/api-e2e/.spec.swcrc new file mode 100644 index 0000000..9a995fe --- /dev/null +++ b/apps/api-e2e/.spec.swcrc @@ -0,0 +1,22 @@ +{ + "jsc": { + "target": "es2017", + "parser": { + "syntax": "typescript", + "decorators": true, + "dynamicImport": true + }, + "transform": { + "decoratorMetadata": true, + "legacyDecorator": true + }, + "keepClassNames": true, + "externalHelpers": true, + "loose": true + }, + "module": { + "type": "es6" + }, + "sourceMaps": true, + "exclude": [] +} diff --git a/apps/api-e2e/eslint.config.mjs b/apps/api-e2e/eslint.config.mjs new file mode 100644 index 0000000..b7f6277 --- /dev/null +++ b/apps/api-e2e/eslint.config.mjs @@ -0,0 +1,3 @@ +import baseConfig from '../../eslint.config.mjs'; + +export default [...baseConfig]; diff --git a/apps/api-e2e/jest.config.cts b/apps/api-e2e/jest.config.cts new file mode 100644 index 0000000..e4ef1e9 --- /dev/null +++ b/apps/api-e2e/jest.config.cts @@ -0,0 +1,21 @@ +import { readFileSync } from 'fs'; + +// Reading the SWC compilation config for the spec files +const swcJestConfig = JSON.parse(readFileSync(`${__dirname}/.spec.swcrc`, 'utf-8')); + +// Disable .swcrc look-up by SWC core because we're passing in swcJestConfig ourselves +swcJestConfig.swcrc = false; + +export default { + displayName: 'api-e2e', + preset: '../../jest.preset.js', + globalSetup: '/src/support/global-setup.ts', + globalTeardown: '/src/support/global-teardown.ts', + setupFiles: ['/src/support/test-setup.ts'], + testEnvironment: 'node', + transform: { + '^.+\\.[tj]s$': ['@swc/jest', swcJestConfig], + }, + moduleFileExtensions: ['ts', 'js', 'html'], + coverageDirectory: 'test-output/jest/coverage', +}; diff --git a/apps/api-e2e/package.json b/apps/api-e2e/package.json new file mode 100644 index 0000000..6142290 --- /dev/null +++ b/apps/api-e2e/package.json @@ -0,0 +1,5 @@ +{ + "name": "@geo-platform/api-e2e", + "version": "0.0.1", + "private": true +} diff --git a/apps/api-e2e/project.json b/apps/api-e2e/project.json new file mode 100644 index 0000000..04bb59e --- /dev/null +++ b/apps/api-e2e/project.json @@ -0,0 +1,53 @@ +{ + "name": "api-e2e", + "implicitDependencies": [ + "api" + ], + "targets": { + "lint": { + "executor": "@nx/eslint:lint", + "options": { + "lintFilePatterns": [ + "{projectRoot}/**/*.ts" + ], + "eslintConfig": "{projectRoot}/eslint.config.mjs", + "fix": true + } + }, + "lint-check": { + "executor": "@nx/eslint:lint", + "options": { + "lintFilePatterns": [ + "{projectRoot}/**/*.ts" + ], + "eslintConfig": "{projectRoot}/eslint.config.mjs" + } + }, + "format": { + "executor": "nx:run-commands", + "options": { + "command": "prettier --write {projectRoot}" + } + }, + "format-check": { + "executor": "nx:run-commands", + "options": { + "command": "prettier --check {projectRoot}" + } + }, + "e2e": { + "executor": "@nx/jest:jest", + "outputs": [ + "{projectRoot}/test-output/jest/coverage" + ], + "options": { + "jestConfig": "apps/api-e2e/jest.config.cts", + "passWithNoTests": true + }, + "dependsOn": [ + "api:build", + "api:serve" + ] + } + } +} diff --git a/apps/api-e2e/src/api/api.spec.ts b/apps/api-e2e/src/api/api.spec.ts new file mode 100644 index 0000000..67d6f72 --- /dev/null +++ b/apps/api-e2e/src/api/api.spec.ts @@ -0,0 +1,11 @@ +import axios from 'axios'; +import { describe, it } from 'vitest'; + +describe.skip('GET /api', () => { + it('should return a message', async () => { + const res = await axios.get(`/api`); + + expect(res.status).toBe(200); + expect(res.data).toEqual({ message: 'Hello API' }); + }); +}); diff --git a/apps/api-e2e/src/support/global-setup.ts b/apps/api-e2e/src/support/global-setup.ts new file mode 100644 index 0000000..9d33abf --- /dev/null +++ b/apps/api-e2e/src/support/global-setup.ts @@ -0,0 +1,16 @@ +import { waitForPortOpen } from '@nx/node/utils'; + +/* eslint-disable */ +var __TEARDOWN_MESSAGE__: string; + +module.exports = async function () { + // Start services that that the app needs to run (e.g. database, docker-compose, etc.). + console.log('\nSetting up...\n'); + + const host = process.env.HOST ?? 'localhost'; + const port = process.env.PORT ? Number(process.env.PORT) : 5000; + await waitForPortOpen(port, { host }); + + // Hint: Use `globalThis` to pass variables to global teardown. + globalThis.__TEARDOWN_MESSAGE__ = '\nTearing down...\n'; +}; diff --git a/apps/api-e2e/src/support/global-teardown.ts b/apps/api-e2e/src/support/global-teardown.ts new file mode 100644 index 0000000..f16fd6a --- /dev/null +++ b/apps/api-e2e/src/support/global-teardown.ts @@ -0,0 +1,9 @@ +import { killPort } from '@nx/node/utils'; + +module.exports = async function () { + // Put clean up logic here (e.g. stopping services, docker-compose, etc.). + // Hint: `globalThis` is shared between setup and teardown. + const port = process.env.PORT ? Number(process.env.PORT) : 5000; + await killPort(port); + console.log(globalThis.__TEARDOWN_MESSAGE__); +}; diff --git a/apps/api-e2e/src/support/test-setup.ts b/apps/api-e2e/src/support/test-setup.ts new file mode 100644 index 0000000..04aa72f --- /dev/null +++ b/apps/api-e2e/src/support/test-setup.ts @@ -0,0 +1,8 @@ +import axios from 'axios'; + +module.exports = async function () { + // Configure axios for tests to use. + const host = process.env.HOST ?? 'localhost'; + const port = process.env.PORT ?? '5000'; + axios.defaults.baseURL = `http://${host}:${port}`; +}; diff --git a/apps/api-e2e/tsconfig.json b/apps/api-e2e/tsconfig.json new file mode 100644 index 0000000..3ae892a --- /dev/null +++ b/apps/api-e2e/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "out-tsc/@geo-platform/api-e2e", + "esModuleInterop": true, + "noUnusedLocals": false, + "noImplicitAny": false + }, + "include": [ + "jest.config.ts", + "src/**/*.ts" + ], + "references": [] +} diff --git a/apps/api/Dockerfile b/apps/api/Dockerfile new file mode 100644 index 0000000..b2598bb --- /dev/null +++ b/apps/api/Dockerfile @@ -0,0 +1,25 @@ +FROM git.jt4d.ru/jt4d/node:24-alpine AS deps + +WORKDIR /app + +COPY ./package.json ./yarn.lock ./ + +RUN yarn install --production --frozen-lockfile && yarn cache clean + +FROM git.jt4d.ru/jt4d/node:24-alpine + +RUN apk add --no-cache tini curl + +COPY --from=deps /app/node_modules /app/node_modules + +COPY ./dist /app + +EXPOSE 5000 +ENV PORT=5000 + +WORKDIR /app + +HEALTHCHECK --interval=30s --timeout=5s --retries=3 --start-period=15s \ + CMD curl -f http://localhost:5000/api/health || exit 1 + +ENTRYPOINT ["/sbin/tini", "--", "node", "main.js"] diff --git a/apps/api/deny-external-plugin.js b/apps/api/deny-external-plugin.js new file mode 100644 index 0000000..175fb4a --- /dev/null +++ b/apps/api/deny-external-plugin.js @@ -0,0 +1,96 @@ +const path = require('path'); + +const colorette = require('colorette'); +const nodeExternals = require('webpack-node-externals'); + +/** + * Обертка на webpack-node-externals с логированием внешних пакетов. + * + * Потребовалась, чтобы переписать то, что настроил NxAppWebpackPlugin. + * + * Заставляет webpack БАНДЛИТЬ пакеты с указанными префиксами (не делать их external). + * Для всех остальных пакетов из node_modules — применяется стандартный nodeExternals. + * + * Использовать совместно с externalDependencies: 'none' в NxAppWebpackPlugin, + * чтобы NxAppWebpackPlugin не добавлял собственный nodeExternals без allowlist. + */ +module.exports.DenyExternalsPlugin = class DenyExternalsPlugin { + constructor(skipExternalPackages) { + // Массив строк-префиксов, например ['@geo-platform/'] + this.skipExternalPackages = skipExternalPackages; + } + + apply(compiler) { + const NAME = 'DenyExternalsPlugin'; + + // Преобразуем строковые префиксы в RegExp для allowlist nodeExternals. + // containsPattern в webpack-node-externals проверяет: regexp.test(request) + const allowlistPatterns = this.skipExternalPackages.map( + (prefix) => new RegExp('^' + prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')), + ); + + // compiler.context устанавливается в NxAppWebpackPlugin.apply() (раньше нас), + // поэтому здесь уже доступно корректное значение (/apps/api). + // Идём два уровня вверх до корня воркспейса, где лежит node_modules. + const modulesDir = path.join(compiler.context, '../../node_modules'); + // Локальный node_modules приложения (apps/api/node_modules/) — пакеты, + // которые не удалось hoisted в корень (например, из-за конфликтов версий). + const localModulesDir = path.join(compiler.context, 'node_modules'); + + // Заменяем externals (NxAppWebpackPlugin с externalDependencies: 'none' + // оставляет compiler.options.externals = []). + // Ставим nodeExternals с нашим allowlist — пакеты из allowlist будут бандлиться. + compiler.options.externals = [ + nodeExternals({ + modulesDir, + additionalModuleDirs: [localModulesDir], + allowlist: allowlistPatterns, + }), + ]; + + // Печатаем ФАКТИЧЕСКИЕ external-модули после сборки графа модулей. + compiler.hooks.compilation.tap(NAME, (compilation) => { + compilation.hooks.finishModules.tap(NAME, (modules) => { + const out = []; + + for (const m of modules) { + const isExternal = + m?.constructor?.name === 'ExternalModule' || + m?.external === true || + typeof m?.externalType === 'string'; + + if (!isExternal) { + continue; + } + + const request = m.userRequest || m.request || m._request || '<>'; + const type = m.externalType || ''; + + out.push({ request, type }); + } + + if (out.length) { + const unique = new Map(); + + for (const { request, type } of out) { + if (!unique.has(request)) { + unique.set(request, type || ''); + } + } + + console.log(`\n── used externals: ${unique.size}`); + + const list = Array.from(unique.entries()) + .map(([req, t]) => ` • ${req} ${colorette.gray(`[${t}]`)}`) + .toSorted(); + + console.log(list.join('\n')); + + console.log(''); + } else { + console.log('\n── used externals (none)\n'); + } + }); + }); + } +}; diff --git a/apps/api/eslint.config.mjs b/apps/api/eslint.config.mjs new file mode 100644 index 0000000..b7f6277 --- /dev/null +++ b/apps/api/eslint.config.mjs @@ -0,0 +1,3 @@ +import baseConfig from '../../eslint.config.mjs'; + +export default [...baseConfig]; diff --git a/apps/api/package.json b/apps/api/package.json new file mode 100644 index 0000000..ca48a8b --- /dev/null +++ b/apps/api/package.json @@ -0,0 +1,18 @@ +{ + "name": "@geo-platform/api", + "version": "0.0.1", + "private": true, + "dependencies": { + "@nestjs/common": "^11.0.0", + "@nestjs/core": "^11.0.0", + "@nestjs/platform-express": "^11.0.0", + "axios": "^1.6.0", + "reflect-metadata": "^0.1.13", + "rxjs": "^7.8.0" + }, + "devDependencies": { + "@nestjs/schematics": "^11.0.0", + "@nestjs/testing": "^11.0.0", + "webpack-cli": "^5.1.4" + } +} diff --git a/apps/api/project.json b/apps/api/project.json new file mode 100644 index 0000000..1cf03a9 --- /dev/null +++ b/apps/api/project.json @@ -0,0 +1,202 @@ +{ + "name": "api", + "$schema": "../../node_modules/nx/schemas/project-schema.json", + "sourceRoot": "apps/api/src", + "projectType": "application", + "tags": [], + "targets": { + "build": { + "executor": "nx:run-commands", + "dependsOn": [ + "db-migrations-list" + ], + "outputs": [ + "{projectRoot}/dist" + ], + "options": { + "commands": [ + "webpack-cli build", + "webpack-cli build --config webpack.data-source.config.js" + ], + "parallel": false, + "args": [ + "--node-env=production" + ], + "cwd": "apps/api" + }, + "configurations": { + "development": { + "args": [ + "--node-env=development" + ] + } + } + }, + "typecheck": { + "executor": "nx:run-commands", + "options": { + "command": "tsc --noEmit -p tsconfig.spec.json", + "cwd": "apps/api" + } + }, + "lint": { + "executor": "@nx/eslint:lint", + "options": { + "lintFilePatterns": [ + "{projectRoot}/**/*.ts" + ], + "eslintConfig": "{projectRoot}/eslint.config.mjs", + "fix": true + } + }, + "lint-check": { + "executor": "@nx/eslint:lint", + "options": { + "lintFilePatterns": [ + "{projectRoot}/**/*.ts" + ], + "eslintConfig": "{projectRoot}/eslint.config.mjs" + } + }, + "format": { + "executor": "nx:run-commands", + "options": { + "command": "prettier --write {projectRoot}" + } + }, + "format-check": { + "executor": "nx:run-commands", + "options": { + "command": "prettier --check {projectRoot}" + } + }, + "serve": { + "continuous": true, + "executor": "@nx/js:node", + "defaultConfiguration": "development", + "dependsOn": [ + "build" + ], + "options": { + "buildTarget": "api:build", + "runBuildTargetDependencies": false + }, + "configurations": { + "development": { + "buildTarget": "api:build:development" + }, + "production": { + "buildTarget": "api:build:production" + } + } + }, + "prune-lockfile": { + "dependsOn": [ + "build" + ], + "cache": true, + "executor": "@nx/js:prune-lockfile", + "outputs": [ + "{workspaceRoot}/apps/api/dist/package.json", + "{workspaceRoot}/apps/api/dist/yarn.lock" + ], + "options": { + "buildTarget": "build" + } + }, + "copy-workspace-modules": { + "dependsOn": [ + "build" + ], + "cache": true, + "outputs": [ + "{workspaceRoot}/apps/api/dist/workspace_modules" + ], + "executor": "@nx/js:copy-workspace-modules", + "options": { + "buildTarget": "build" + } + }, + "prune": { + "dependsOn": [ + "prune-lockfile", + "copy-workspace-modules" + ], + "executor": "nx:noop" + }, + "db-migrations-list": { + "executor": "nx:run-commands", + "options": { + "command": "ts-node", + "args": [ + "--transpile-only", + "tools/buildDataSource.ts" + ] + } + }, + "db-show": { + "executor": "nx:run-commands", + "options": { + "command": "typeorm-ts-node-commonjs", + "args": [ + "migration:show", + "--dataSource=apps/api/src/config/typeorm.config.ts" + ] + } + }, + "db-migrate": { + "executor": "nx:run-commands", + "options": { + "command": "typeorm-ts-node-commonjs", + "args": [ + "migration:run", + "--dataSource=apps/api/src/config/typeorm.config.ts" + ] + } + }, + "db-revert": { + "executor": "nx:run-commands", + "options": { + "command": "typeorm-ts-node-commonjs", + "args": [ + "migration:revert", + "--dataSource=apps/api/src/config/typeorm.config.ts" + ] + } + }, + "db-drop": { + "executor": "nx:run-commands", + "options": { + "command": "typeorm-ts-node-commonjs", + "args": [ + "schema:drop", + "--dataSource=apps/api/src/config/typeorm.config.ts" + ] + } + }, + "db-snapshot": { + "executor": "nx:run-commands", + "options": { + "command": "ts-node", + "args": [ + "tools/dbSnapshot.ts" + ] + } + }, + "db-restore": { + "executor": "nx:run-commands", + "options": { + "command": "ts-node", + "args": [ + "tools/dbRestore.ts" + ] + } + }, + "test": { + "executor": "@nx/vitest:test", + "options": { + "configFile": "apps/api/vitest.config.ts" + } + } + } +} diff --git a/apps/api/src/app/app.controller.ts b/apps/api/src/app/app.controller.ts new file mode 100644 index 0000000..f72a1c1 --- /dev/null +++ b/apps/api/src/app/app.controller.ts @@ -0,0 +1,12 @@ +import { Controller, Get } from '@nestjs/common'; +import { AppService } from './app.service'; + +@Controller() +export class AppController { + constructor(private readonly appService: AppService) {} + + @Get() + getData() { + return this.appService.getData(); + } +} diff --git a/apps/api/src/app/app.module.ts b/apps/api/src/app/app.module.ts new file mode 100644 index 0000000..da156b4 --- /dev/null +++ b/apps/api/src/app/app.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { AppController } from './app.controller'; +import { AppService } from './app.service'; + +@Module({ + imports: [], + controllers: [AppController], + providers: [AppService], +}) +export class AppModule {} diff --git a/apps/api/src/app/app.service.ts b/apps/api/src/app/app.service.ts new file mode 100644 index 0000000..42eee86 --- /dev/null +++ b/apps/api/src/app/app.service.ts @@ -0,0 +1,8 @@ +import { Injectable } from '@nestjs/common'; + +@Injectable() +export class AppService { + getData(): { message: string } { + return { message: 'Hello API' }; + } +} diff --git a/apps/api/src/health/health.controller.ts b/apps/api/src/health/health.controller.ts new file mode 100644 index 0000000..8be79cd --- /dev/null +++ b/apps/api/src/health/health.controller.ts @@ -0,0 +1,47 @@ +import { Controller, Get } from '@nestjs/common'; +import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger'; +import { HealthCheck, HealthCheckService, TypeOrmHealthIndicator } from '@nestjs/terminus'; + +declare const __APP_VERSION__: string; + +@ApiTags('Health Check') +@Controller('health') +export class HealthController { + constructor( + private health: HealthCheckService, + private db: TypeOrmHealthIndicator, + ) {} + + @Get() + @HealthCheck() + @ApiOperation({ summary: 'Проверка состояния приложения' }) + @ApiResponse({ + status: 200, + description: 'Приложение работает нормально', + schema: { + type: 'object', + properties: { + status: { type: 'string', example: 'ok' }, + version: { type: 'string', example: 'v1.2.3' }, + info: { + type: 'object', + properties: { + database: { + type: 'object', + properties: { + status: { type: 'string', example: 'up' }, + }, + }, + }, + }, + }, + }, + }) + async check() { + const result = await this.health.check([() => this.db.pingCheck('database')]); + return { + ...result, + version: __APP_VERSION__, + }; + } +} diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts new file mode 100644 index 0000000..ab2a7f1 --- /dev/null +++ b/apps/api/src/main.ts @@ -0,0 +1,46 @@ +import { NestFactory } from '@nestjs/core'; +import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; + +import { AppModule } from './app/app.module'; + +async function start() { + const PORT = process.env.PORT || 5000; + + const app = await NestFactory.create(AppModule); + + // настройка swaggera + const config = new DocumentBuilder() + .setTitle('GEO Helm Backend') + .setDescription('Documentation for the GEO Helm Backend') + .setVersion('1.0.0') + .addBearerAuth( + { + type: 'http', + scheme: 'bearer', + bearerFormat: 'JWT', + name: 'JWT', + description: 'Enter JWT token', + in: 'header', + }, + 'JWT-auth', + ) + .build(); + app.enableShutdownHooks(); + app.setGlobalPrefix('api'); + const server = app.getHttpServer(); + server.setTimeout(20 * 60 * 1000); // 20-minute window for heavy calculations + // подключаем swagger к приложению и указываем путь к документации + const document = SwaggerModule.createDocument(app, config); + SwaggerModule.setup('/api/docs', app, document); + app.enableCors({ + origin: + process.env.NODE_ENV === 'development' + ? ['http://localhost:5173'] + : ['https://app.igeo.pro'], + methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', + allowedHeaders: 'Content-Type, Authorization', + credentials: true, + }); + await app.listen(PORT, () => console.log(`Server started on ${PORT}`)); +} +start(); diff --git a/apps/api/src/test-setup.ts b/apps/api/src/test-setup.ts new file mode 100644 index 0000000..d2c9bc6 --- /dev/null +++ b/apps/api/src/test-setup.ts @@ -0,0 +1 @@ +import 'reflect-metadata'; diff --git a/apps/api/tsconfig.app.json b/apps/api/tsconfig.app.json new file mode 100644 index 0000000..2cc19d9 --- /dev/null +++ b/apps/api/tsconfig.app.json @@ -0,0 +1,24 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "types": [ + "node", + "multer" + ], + "rootDir": "src", + "tsBuildInfoFile": "dist/tsconfig.app.tsbuildinfo", + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "target": "es2024" + }, + "include": [ + "src/**/*.ts" + ], + "exclude": [ + "eslint.config.js", + "eslint.config.cjs", + "eslint.config.mjs", + "src/**/*.spec.ts" + ] +} diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json new file mode 100644 index 0000000..e23d75a --- /dev/null +++ b/apps/api/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.base.json", + "files": [], + "include": [], + "references": [ + { + "path": "./tsconfig.app.json" + }, + { + "path": "./tsconfig.spec.json" + } + ] +} diff --git a/apps/api/tsconfig.spec.json b/apps/api/tsconfig.spec.json new file mode 100644 index 0000000..b3d461b --- /dev/null +++ b/apps/api/tsconfig.spec.json @@ -0,0 +1,16 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "./out-tsc/vitest", + "types": [ + "node", + "multer" + ], + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "target": "es2024" + }, + "include": [ + "src/**/*.ts" + ] +} diff --git a/apps/api/vitest.config.ts b/apps/api/vitest.config.ts new file mode 100644 index 0000000..e679f2a --- /dev/null +++ b/apps/api/vitest.config.ts @@ -0,0 +1,35 @@ +/// +import { resolve } from 'path'; + +import swc from 'unplugin-swc'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + root: import.meta.dirname, + // unplugin-swc emits decorator metadata that esbuild cannot produce; TypeORM relies on it. + plugins: [ + swc.vite({ + jsc: { + parser: { syntax: 'typescript', decorators: true }, + transform: { decoratorMetadata: true, legacyDecorator: true }, + target: 'es2022', + }, + }), + ], + resolve: { + alias: { + '@geo-platform/api': resolve(import.meta.dirname, 'src'), + }, + }, + test: { + name: '@geo-platform/api', + globals: true, + environment: 'node', + include: ['src/**/*.spec.ts'], + setupFiles: ['src/test-setup.ts'], + coverage: { + reportsDirectory: './test-output/vitest/coverage', + provider: 'v8', + }, + }, +}); diff --git a/apps/api/webpack.base.js b/apps/api/webpack.base.js new file mode 100644 index 0000000..5727252 --- /dev/null +++ b/apps/api/webpack.base.js @@ -0,0 +1,51 @@ +const { join } = require('path'); + +const { NxAppWebpackPlugin } = require('@nx/webpack/app-plugin'); + +const { DenyExternalsPlugin } = require('./deny-external-plugin'); + +/** + * Общая база для двух бандлов api: main.js и data-source.js. + * + * Вынесена, чтобы alias, tsConfig и связка externalDependencies: 'none' + + * DenyExternalsPlugin задавались один раз: если они разойдутся, data-source.js + * получит второй экземпляр typeorm и это всплывёт только на реальном деплое, + * в `docker exec … migration:run`. + * + * @param {object} params + * @param {object} params.output — поверх output базы (filename, clean, library, …) + * @param {object} params.nxPlugin — поверх опций NxAppWebpackPlugin (main, sourceMap, …) + * @param {Array} [params.plugins] — дополнительные плагины после DenyExternalsPlugin + */ +function createApiWebpackConfig({ output, nxPlugin, plugins = [] }) { + return { + output: { + path: join(__dirname, 'dist'), + ...output, + }, + resolve: { + alias: { + '@geo-platform/api': join(__dirname, 'src'), + }, + extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'], + }, + plugins: [ + new NxAppWebpackPlugin({ + target: 'node', + compiler: 'tsc', + tsConfig: './tsconfig.app.json', + optimization: false, + outputHashing: 'none', + externalDependencies: 'none', + ...nxPlugin, + }), + // Обязательно в паре с externalDependencies: 'none'. Без плагина webpack + // вкомпилирует второй экземпляр typeorm, и он перестанет быть тем же + // модулем, что грузит CLI. + new DenyExternalsPlugin(['@geo-platform/']), + ...plugins, + ], + }; +} + +module.exports = { createApiWebpackConfig }; diff --git a/apps/api/webpack.config.js b/apps/api/webpack.config.js new file mode 100644 index 0000000..ec05c85 --- /dev/null +++ b/apps/api/webpack.config.js @@ -0,0 +1,22 @@ +const webpack = require('webpack'); + +const { createApiWebpackConfig } = require('./webpack.base'); + +module.exports = createApiWebpackConfig({ + output: { + clean: true, + ...(process.env.NODE_ENV !== 'production' && { + devtoolModuleFilenameTemplate: '[absolute-resource-path]', + }), + }, + nxPlugin: { + main: './src/main.ts', + generatePackageJson: true, + sourceMap: true, + }, + plugins: [ + new webpack.DefinePlugin({ + __APP_VERSION__: JSON.stringify(process.env.APP_VERSION || 'unknown'), + }), + ], +});