api: приложение NestJS и e2e-тесты

Каркас api: NestJS со сборкой через webpack, health-контроллер с версией
и статусом БД,
Dockerfile, тесты Vitest и e2e-тесты на Jest.
This commit is contained in:
arswarog committed 2026-10-27 10:43:43 +03:00
1 parent 94e5e09218
commit 94f9b06527
27 files changed
+791

No files matched your search

+22
View File
@@ -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": []
}
+3
View File
@@ -0,0 +1,3 @@
import baseConfig from '../../eslint.config.mjs';
export default [...baseConfig];
+21
View File
@@ -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: '<rootDir>/src/support/global-setup.ts',
globalTeardown: '<rootDir>/src/support/global-teardown.ts',
setupFiles: ['<rootDir>/src/support/test-setup.ts'],
testEnvironment: 'node',
transform: {
'^.+\\.[tj]s$': ['@swc/jest', swcJestConfig],
},
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: 'test-output/jest/coverage',
};
+5
View File
@@ -0,0 +1,5 @@
{
"name": "@geo-platform/api-e2e",
"version": "0.0.1",
"private": true
}
+53
View File
@@ -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"
]
}
}
}
+11
View File
@@ -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' });
});
});
+16
View File
@@ -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';
};
@@ -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__);
};
+8
View File
@@ -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}`;
};
+14
View File
@@ -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": []
}
+25
View File
@@ -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"]
+96
View File
@@ -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() (раньше нас),
// поэтому здесь уже доступно корректное значение (<workspace>/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 || '<<unknown>>';
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');
}
});
});
}
};
+3
View File
@@ -0,0 +1,3 @@
import baseConfig from '../../eslint.config.mjs';
export default [...baseConfig];
+18
View File
@@ -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"
}
}
+202
View File
@@ -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"
}
}
}
}
+12
View File
@@ -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();
}
}
+10
View File
@@ -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 {}
+8
View File
@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getData(): { message: string } {
return { message: 'Hello API' };
}
}
+47
View File
@@ -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__,
};
}
}
+46
View File
@@ -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();
+1
View File
@@ -0,0 +1 @@
import 'reflect-metadata';
+24
View File
@@ -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"
]
}
+13
View File
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.base.json",
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.spec.json"
}
]
}
+16
View File
@@ -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"
]
}
+35
View File
@@ -0,0 +1,35 @@
/// <reference types='vitest' />
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',
},
},
});
+51
View File
@@ -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 };
+22
View File
@@ -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'),
}),
],
});