Initial commit
CI / Сборка (push) Canceled after 0s
CI / Деплой на стейджинг (push) Canceled after 0s
CI / Проверка кода (push) Canceled after 0s
CI / Сборка (pull_request) Successful in 1m33s
Стенд master
CI / Деплой на стейджинг (pull_request) Successful in 8s
CI / Проверка кода (pull_request) Successful in 1m32s
CI / Сборка (push) Canceled after 0s
CI / Деплой на стейджинг (push) Canceled after 0s
CI / Проверка кода (push) Canceled after 0s
CI / Сборка (pull_request) Successful in 1m33s
Стенд master
CI / Деплой на стейджинг (pull_request) Successful in 8s
CI / Проверка кода (pull_request) Successful in 1m32s
This commit is contained in:
commit
1420aad1ae
92 files changed
+19114
No files matched your search
@@ -0,0 +1,7 @@
|
||||
node_modules
|
||||
.git
|
||||
**/dist
|
||||
.idea
|
||||
.vscode
|
||||
.cursor
|
||||
.husky
|
||||
@@ -0,0 +1,14 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
indent_size = 4
|
||||
indent_style = space
|
||||
insert_final_newline = true
|
||||
max_line_length = 120
|
||||
tab_width = 2
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[{*.json,.html,.babelrc,.eslintrc,.prettierrc,.stylelintrc,jest.config}]
|
||||
tab_width = 2
|
||||
@@ -0,0 +1,156 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize]
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.head_ref || github.ref_name }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Сборка
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Login to Gitea Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: git.jt4d.ru
|
||||
username: ${{ vars.REGISTRY_USER }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: yarn install --frozen-lockfile
|
||||
|
||||
- name: Check branch name
|
||||
run: yarn lint:branch-name
|
||||
|
||||
- name: Check migrations list
|
||||
run: yarn ts-node tools/buildDataSource.ts --check
|
||||
|
||||
- name: Compute version
|
||||
id: version
|
||||
env:
|
||||
REF_NAME: ${{ github.head_ref || github.ref_name }}
|
||||
run: echo "VERSION=$REF_NAME-$(git rev-parse --short HEAD)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build
|
||||
run: yarn build
|
||||
env:
|
||||
APP_VERSION: ${{ steps.version.outputs.VERSION }}
|
||||
|
||||
- name: Check data-source
|
||||
run: yarn ts-node tools/checkDataSource.ts
|
||||
|
||||
- name: Build web docker image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: apps/web
|
||||
file: apps/web/Dockerfile
|
||||
push: true
|
||||
build-args: |
|
||||
CADDYFILE=Caddyfile.staging
|
||||
tags: git.jt4d.ru/${{ github.repository }}/web:${{ github.head_ref || github.ref_name }}
|
||||
cache-from: git.jt4d.ru/${{ github.repository }}/web:latest
|
||||
labels: |
|
||||
org.opencontainers.image.ref.name=${{ github.head_ref || github.ref_name }}
|
||||
|
||||
- name: Copy
|
||||
run: cp yarn.lock apps/api/
|
||||
|
||||
- name: Build api docker image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: apps/api
|
||||
file: apps/api/Dockerfile
|
||||
push: true
|
||||
tags: git.jt4d.ru/${{ github.repository }}/api:${{ github.head_ref || github.ref_name }}
|
||||
cache-from: git.jt4d.ru/${{ github.repository }}/api:latest
|
||||
labels: |
|
||||
org.opencontainers.image.ref.name=${{ github.head_ref || github.ref_name }}
|
||||
|
||||
deploy-staging:
|
||||
name: Деплой на стейджинг
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
env:
|
||||
DEPLOY_URL: https://${{ github.head_ref || github.ref_name }}.it-smi.jt4d.ru.net
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Deploy via SSH
|
||||
uses: jt4d-lab/ssh-action@v1
|
||||
env:
|
||||
BRANCH: ${{ github.head_ref || github.ref_name }}
|
||||
with:
|
||||
host: ${{ vars.STAGING_HOST }}
|
||||
username: ${{ vars.STAGING_USER }}
|
||||
key: ${{ secrets.STAGING_SSH_PRIVATE_KEY }}
|
||||
port: ${{ vars.STAGING_PORT }}
|
||||
workdir: /home/${{ vars.STAGING_USER }}/${{ github.event.repository.name }}_${{ github.head_ref || github.ref_name }}
|
||||
files: docker-compose.staging.yml
|
||||
script_stop: true
|
||||
envs: BRANCH
|
||||
script: |
|
||||
mv -f docker-compose.staging.yml docker-compose.yml
|
||||
# \${BRANCH} — литеральный плейсхолдер в docker-compose.staging.yml,
|
||||
# $BRANCH — имя ветки из окружения.
|
||||
sed -i "s/\${BRANCH}/$BRANCH/g" docker-compose.yml
|
||||
docker compose pull --quiet
|
||||
staging-db-postgres create "${{ github.repository }}" "$BRANCH"
|
||||
docker compose down
|
||||
docker compose up -d
|
||||
|
||||
echo "Список миграций"
|
||||
docker compose exec -T api node_modules/.bin/typeorm migration:show -d data-source.js
|
||||
echo "Применение миграций"
|
||||
docker compose exec -T api node_modules/.bin/typeorm migration:run -t each -d data-source.js
|
||||
|
||||
docker system prune -f
|
||||
|
||||
- name: Set deployment status
|
||||
env:
|
||||
BRANCH: ${{ github.head_ref || github.ref_name }}
|
||||
run: |
|
||||
curl -s -X POST \
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"state": "success",
|
||||
"context": "Стенд",
|
||||
"description": "'"$BRANCH"'",
|
||||
"target_url": "'"$DEPLOY_URL"'"
|
||||
}' \
|
||||
"${{ github.server_url }}/api/v1/repos/${{ github.repository }}/statuses/${{ github.sha }}"
|
||||
|
||||
- name: Write stand URL to summary
|
||||
run: echo "**Стенд:** $DEPLOY_URL" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
check:
|
||||
name: Проверка кода
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Login to Gitea Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: git.jt4d.ru
|
||||
username: ${{ vars.REGISTRY_USER }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: yarn install --frozen-lockfile
|
||||
|
||||
- name: Lint
|
||||
run: yarn lint:check
|
||||
@@ -0,0 +1,63 @@
|
||||
name: Cleanup
|
||||
|
||||
on:
|
||||
delete:
|
||||
pull_request:
|
||||
types: [closed]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: cleanup-${{ github.event.pull_request.head.ref || github.event.ref || github.ref_name }}
|
||||
|
||||
jobs:
|
||||
cleanup:
|
||||
name: Удаление стенда
|
||||
runs-on: ubuntu-latest
|
||||
if: >-
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
(github.event_name == 'delete' && github.event.ref_type == 'branch') ||
|
||||
(github.event_name == 'pull_request' &&
|
||||
github.event.pull_request.head.repo.full_name == github.repository)
|
||||
steps:
|
||||
- name: Удаление стенда
|
||||
uses: jt4d-lab/ssh-action@v1
|
||||
with:
|
||||
host: ${{ vars.STAGING_HOST }}
|
||||
username: ${{ vars.STAGING_USER }}
|
||||
key: ${{ secrets.STAGING_SSH_PRIVATE_KEY }}
|
||||
port: ${{ vars.STAGING_PORT }}
|
||||
script_stop: true
|
||||
script: |
|
||||
BRANCH_NAME="${{ github.event.ref || github.event.pull_request.head.ref || github.ref_name }}"
|
||||
BRANCH_NAME="${BRANCH_NAME#refs/heads/}"
|
||||
DEPLOY_DIR="/home/${{ vars.STAGING_USER }}/${{ github.event.repository.name }}_${BRANCH_NAME}"
|
||||
echo "Deleting stand for branch: ${BRANCH_NAME}"
|
||||
echo $DEPLOY_DIR
|
||||
# Стек гасим до удаления базы: DROP DATABASE не пройдёт при живом подключении api.
|
||||
if [ -d "$DEPLOY_DIR" ]; then
|
||||
cd "$DEPLOY_DIR"
|
||||
docker compose down --rmi all || true
|
||||
fi
|
||||
staging-db-postgres delete "${{ github.repository }}" "$BRANCH_NAME"
|
||||
cd "$HOME"
|
||||
rm -rf "$DEPLOY_DIR"
|
||||
docker system prune -f
|
||||
|
||||
- name: Удаление docker образов
|
||||
run: |
|
||||
BRANCH_NAME="${{ github.event.ref || github.event.pull_request.head.ref || github.ref_name }}"
|
||||
BRANCH_NAME="${BRANCH_NAME#refs/heads/}"
|
||||
OWNER="${{ github.repository_owner }}"
|
||||
REPO_NAME="${{ github.event.repository.name }}"
|
||||
SERVER="${{ github.server_url }}"
|
||||
|
||||
for IMAGE in web api; do
|
||||
PACKAGE="${REPO_NAME}%2F${IMAGE}"
|
||||
URL="${SERVER}/api/v1/packages/${OWNER}/container/${PACKAGE}/${BRANCH_NAME}"
|
||||
echo "Deleting ${URL}"
|
||||
curl -i -sS \
|
||||
-X DELETE \
|
||||
-H "Authorization: token ${{ secrets.SERVICE_BOT_TOKEN }}" \
|
||||
"${URL}" || true
|
||||
echo
|
||||
done
|
||||
@@ -0,0 +1,40 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
main:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
filter: tree:0
|
||||
fetch-depth: 0
|
||||
|
||||
# This enables task distribution via Nx Cloud
|
||||
# Run this command as early as possible, before dependencies are installed
|
||||
# Learn more at https://nx.dev/docs/reference/nx-cloud-cli#npx-nxcloud-startcirun
|
||||
- run: npx nx start-ci-run --distribute-on="3 linux-medium-js" --stop-agents-after="e2e"
|
||||
|
||||
# Cache node_modules
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 24
|
||||
cache: 'npm'
|
||||
|
||||
- run: npm ci
|
||||
|
||||
# Prepend any command with "nx record --" to record its logs to Nx Cloud
|
||||
- run: npx nx record -- npx nx format:check --base="remotes/origin/main"
|
||||
- run: npx nx run-many -t lint test build typecheck e2e
|
||||
# Nx Cloud recommends fixes for failures to help you get CI green faster. Learn more: https://nx.dev/docs/features/ci-features/self-healing-ci
|
||||
- run: npx nx fix-ci
|
||||
if: always()
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
# See https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files for more about ignoring files.
|
||||
|
||||
# compiled output
|
||||
dist
|
||||
tmp
|
||||
out-tsc
|
||||
|
||||
# dependencies
|
||||
node_modules
|
||||
|
||||
# IDEs and editors
|
||||
/.idea
|
||||
.project
|
||||
.classpath
|
||||
.c9/
|
||||
*.launch
|
||||
.settings/
|
||||
*.sublime-workspace
|
||||
|
||||
# IDE - VSCode
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
|
||||
# misc
|
||||
/.sass-cache
|
||||
/connect.lock
|
||||
/coverage
|
||||
/libpeerconnection.log
|
||||
npm-debug.log
|
||||
yarn-error.log
|
||||
testem.log
|
||||
/typings
|
||||
|
||||
# System Files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
.nx/cache
|
||||
.nx/workspace-data
|
||||
.cursor/rules/nx-rules.mdc
|
||||
.github/instructions/nx.instructions.md
|
||||
|
||||
.claude/worktrees
|
||||
.claude/settings.local.json
|
||||
.nx/polygraph
|
||||
.nx/self-healing
|
||||
.nx/migrate-runs
|
||||
|
||||
vite.config.*.timestamp*
|
||||
vitest.config.*.timestamp*
|
||||
|
||||
.env
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
yarn lint-staged
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
yarn lint:branch-name
|
||||
@@ -0,0 +1,8 @@
|
||||
# Add files here to ignore them from prettier formatting
|
||||
/dist
|
||||
/coverage
|
||||
/.nx/cache
|
||||
/.nx/workspace-data
|
||||
.nx/self-healing
|
||||
/.claude
|
||||
/.agents
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"printWidth": 100,
|
||||
"useTabs": false,
|
||||
"tabWidth": 4,
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"bracketSpacing": true,
|
||||
"singleAttributePerLine": true,
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["*.json"],
|
||||
"options": {
|
||||
"printWidth": 10
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": ["*.md", "*.mdx"],
|
||||
"options": {
|
||||
"proseWrap": "always"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"extends": [
|
||||
"stylelint-config-standard",
|
||||
"stylelint-config-recess-order",
|
||||
"stylelint-config-standard-scss",
|
||||
"stylelint-prettier/recommended",
|
||||
"stylelint-config-prettier-scss"
|
||||
],
|
||||
"plugins": [
|
||||
"stylelint-order",
|
||||
"stylelint-scss"
|
||||
],
|
||||
"rules": {
|
||||
"scss/at-rule-no-unknown": [
|
||||
true,
|
||||
{
|
||||
"ignoreAtRules": [
|
||||
"tailwind",
|
||||
"apply",
|
||||
"layer",
|
||||
"screen",
|
||||
"responsive",
|
||||
"variants",
|
||||
"config",
|
||||
"source",
|
||||
"theme",
|
||||
"utility",
|
||||
"custom-variant",
|
||||
"plugin"
|
||||
]
|
||||
}
|
||||
],
|
||||
"selector-pseudo-class-no-unknown": [
|
||||
true,
|
||||
{
|
||||
"ignorePseudoClasses": [
|
||||
"global"
|
||||
]
|
||||
}
|
||||
],
|
||||
"max-nesting-depth": [
|
||||
3,
|
||||
{
|
||||
"ignore": [
|
||||
"blockless-at-rules",
|
||||
"pseudo-classes"
|
||||
]
|
||||
}
|
||||
],
|
||||
"selector-class-pattern": null,
|
||||
"scss/dollar-variable-pattern": null,
|
||||
"custom-property-pattern": null,
|
||||
"selector-id-pattern": null,
|
||||
"no-descending-specificity": null,
|
||||
"order/order": [
|
||||
"custom-properties",
|
||||
"declarations",
|
||||
{
|
||||
"type": "at-rule",
|
||||
"name": "media"
|
||||
},
|
||||
{
|
||||
"type": "rule",
|
||||
"selector": "^&::(before|after)"
|
||||
},
|
||||
{
|
||||
"type": "rule",
|
||||
"selector": "^&:\\w"
|
||||
},
|
||||
{
|
||||
"type": "rule",
|
||||
"selector": "^&_"
|
||||
},
|
||||
{
|
||||
"type": "rule",
|
||||
"selector": "^."
|
||||
}
|
||||
],
|
||||
"color-hex-length": null
|
||||
},
|
||||
"ignoreFiles": [
|
||||
"coverage/**/*",
|
||||
"apps/*/dist/**/*",
|
||||
"dist/**/*"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
# AGENTS.md
|
||||
|
||||
Инструкции для ИИ-агентов при работе с этим репозиторием: обзор, команды, архитектура и конвенции,
|
||||
которые нельзя вывести из кода.
|
||||
|
||||
## Project Overview
|
||||
|
||||
Монорепозиторий Nx с тремя приложениями:
|
||||
|
||||
- **api** — NestJS бэкенд (TypeORM + PostgreSQL), порт 5000, глобальный префикс `/api`, Swagger UI
|
||||
на `/api/docs`
|
||||
- **web** — React фронтенд (Vite), порт 5173, проксирует `/api/*` на бэкенд
|
||||
- **api-e2e** — E2E-тесты на Jest для API
|
||||
|
||||
Package manager: **yarn** (v1 classic). Версия указана в поле `packageManager` в `package.json`. Все
|
||||
задачи запускаются через Nx, а не напрямую через инструменты.
|
||||
|
||||
## Common Commands
|
||||
|
||||
```bash
|
||||
# Все задачи через Nx (не напрямую)
|
||||
yarn nx run api:serve # Запуск бэкенда
|
||||
yarn nx run web:serve # Запуск фронтенда
|
||||
yarn nx run-many -t serve # Запуск всех приложений
|
||||
|
||||
yarn nx run api:build # Сборка бэкенда (webpack)
|
||||
yarn nx run web:build # Сборка фронтенда (vite)
|
||||
|
||||
yarn nx run api:test # Тесты бэкенда (vitest)
|
||||
yarn nx run web:test # Тесты фронтенда (vitest)
|
||||
yarn nx run api:test -- --testPathPattern="users" # Один тест-файл
|
||||
|
||||
yarn nx run api-e2e:e2e # E2E-тесты
|
||||
|
||||
yarn nx run api:lint # ESLint для api
|
||||
yarn nx run web:lint # ESLint для web
|
||||
yarn lint # ESLint + Prettier для всего (с автофиксом)
|
||||
yarn lint:check # Проверка без автофикса
|
||||
|
||||
yarn nx run api:db-show # Список миграций и их статус
|
||||
yarn nx run api:db-migrate # Применить непримененные миграции
|
||||
yarn nx run api:db-migrations-list # Перегенерировать список миграций
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
### Backend (apps/api)
|
||||
|
||||
- NestJS модульная архитектура: модуль — рамка, внутри которой код разложен по слоям
|
||||
`Controller → Service → Data Access Layer`; наружу модуль отдаёт только то, что осознанно
|
||||
экспортирует. Подробности — `docs/50-developing/01-api-layers.md`
|
||||
- Swagger UI доступен на `/api/docs`
|
||||
- Сборка: `db-migrations-list` (через `dependsOn`) → `webpack-cli build` (`main.js`) →
|
||||
`webpack-cli build --config webpack.data-source.config.js` (`data-source.js`), последовательно
|
||||
(`parallel: false`). Запуск через `@nx/js:node`
|
||||
|
||||
#### Миграции БД
|
||||
|
||||
- Миграции лежат по модулям: `apps/api/src/<module>/migrations/`
|
||||
- Список миграций **генерируется статически** (`tools/buildDataSource.ts` сканирует
|
||||
`apps/api/src/**/migrations/` → `apps/api/src/migrations.ts`), потому что webpack не умеет
|
||||
runtime-glob
|
||||
- Имя файла обязано начинаться с **13-значного** timestamp, а имя класса — оканчиваться тем же
|
||||
timestamp: TypeORM берёт его как `parseInt(className.substr(-13))`. Расхождение валит сборку
|
||||
- **После добавления или удаления миграции список нужно перегенерировать и закоммитить**
|
||||
(`yarn nx run api:db-migrations-list`, либо это сделает `yarn nx run api:build` через
|
||||
`dependsOn`). Иначе CI упадёт на шаге `Check migrations list`
|
||||
- Деплой применяет миграции автоматически (`migration:run -t each` через `docker exec` на проде /
|
||||
`docker compose exec` на стейджинге) — на каждый тег на проде и на каждый push/PR на стейджинге.
|
||||
Автоматического бэкапа перед миграцией нет. Подробнее: `docs/90-deploy/10-migrations.md`
|
||||
- DDL пишется методами `QueryRunner` (`Table`/`TableColumn`), а не строкой SQL; вывод
|
||||
`migration:generate` — черновик, который переписывают. `down` обязателен. Имя таблицы — строковым
|
||||
литералом, а не константой `*_TABLE_NAME`: миграция не должна ломаться от удаления модуля.
|
||||
Data-миграции — отдельным файлом. Перед коммитом — цикл `db-migrate` → `db-revert` → `db-migrate`.
|
||||
Подробнее: `docs/50-developing/20-migrations.md`
|
||||
|
||||
#### Конвенции кода и тестов
|
||||
|
||||
Подробности — `docs/50-developing/`:
|
||||
|
||||
- Сущности — в `entities/` внутри модуля; имя таблицы — константа `*_TABLE_NAME` рядом с сущностью
|
||||
(в коде приложения используется везде, в миграциях — нет); колонки — `camelCase`
|
||||
- Весь доступ к БД — в `*.dal.ts`: `@InjectRepository`/`Repository`/`DataSource` допустимы только
|
||||
там. DAL приватен для модуля (не в `exports`), наружу модуль отдаёт публичные сервисы
|
||||
- Тесты — рядом с тестируемым файлом, расширение `.test.ts`; DAL юнит-тестами не покрывается
|
||||
|
||||
### Frontend (apps/web)
|
||||
|
||||
- React + Vite + React Router; стили — Tailwind CSS
|
||||
- Слои идут строго в одну сторону: `app → pages → @modules → common`; `widgets` и `entities`
|
||||
существуют только внутри модуля, обратные зависимости запрещены. Границы объявляются баррелями,
|
||||
схема слоёв — в `apps/web/weld.config.mjs`. Подробности — `docs/50-developing/02-web-layers.md`
|
||||
- Оболочка, шапка и тема — `docs/50-developing/04-ui-shell.md`
|
||||
- Тесты: Vitest с jsdom
|
||||
|
||||
### TypeScript Paths
|
||||
|
||||
Определены в `tsconfig.base.json`:
|
||||
|
||||
- `@it-smi/api/*` → `apps/api/src/*`
|
||||
- `@it-smi/web/*` → `apps/web/src/*`
|
||||
|
||||
При переименовании воркспейса правятся и `paths`, и `customConditions`.
|
||||
|
||||
## Данные для разработки
|
||||
|
||||
- `db-snapshot/*.json` — снапшоты dev-БД для локальной разработки (см. `tools/dbSnapshot.ts` /
|
||||
`dbRestore.ts`).
|
||||
|
||||
## Документация (`docs/`)
|
||||
|
||||
- **Весь новый код должен соответствовать документации в `docs/`.** Существующий код под неё не
|
||||
переписывается — приводится к ней по мере того, как его всё равно затрагивают. Отдельные документы
|
||||
эту оговорку не повторяют
|
||||
- `.md`-файлы в `docs/` компилируются как MDX (Docusaurus) — в обычном тексте (вне code fence
|
||||
` ``` ` и вне inline-код-спанов `` ` ``
|
||||
`` `) нельзя использовать `{...}` и `<` перед небуквенным/нецифро-небуквенным символом или сразу перед словом (например, `<=`, `<lang>`, `<repo>`), иначе сборка падает с `MDX compilation failed`. Внутри code fence и inline-код-спанов такие символы безопасны — MDX не парсит их содержимое как JSX/выражения. Сравнения вида `<= N` замените на `≤ N` (аналогично `>=` → `≥`), а плейсхолдеры вроде `<lang>` — переносите в backtick-код (``
|
||||
`<lang>` ``) или переформулируйте текст
|
||||
|
||||
## Code Quality
|
||||
|
||||
- ESLint 9 flat config (корневой `eslint.config.mjs`)
|
||||
- Prettier для форматирования
|
||||
- Husky + lint-staged: автоформатирование при коммите
|
||||
- `@nx/enforce-module-boundaries` включён
|
||||
|
||||
<!-- nx configuration start-->
|
||||
<!-- Leave the start & end comments to automatically receive updates. -->
|
||||
|
||||
## General Guidelines for working with Nx
|
||||
|
||||
- For navigating/exploring the workspace, invoke the `nx-workspace` skill first - it has patterns
|
||||
for querying projects, targets, and dependencies
|
||||
- When running tasks (for example build, lint, test, e2e, etc.), always prefer running the task
|
||||
through `nx` (i.e. `nx run`, `nx run-many`, `nx affected`) instead of using the underlying tooling
|
||||
directly
|
||||
- Prefix nx commands with the workspace's package manager (e.g., `pnpm nx build`,
|
||||
`npm exec nx test`) - avoids using globally installed CLI
|
||||
- You have access to the Nx MCP server and its tools, use them to help the user
|
||||
- For Nx plugin best practices, check `node_modules/@nx/<plugin>/PLUGIN.md`. Not all plugins have
|
||||
this file - proceed without it if unavailable.
|
||||
- NEVER guess CLI flags - always check nx_docs or `--help` first when unsure
|
||||
|
||||
## Scaffolding & Generators
|
||||
|
||||
- For scaffolding tasks (creating apps, libs, project structure, setup), ALWAYS invoke the
|
||||
`nx-generate` skill FIRST before exploring or calling MCP tools
|
||||
|
||||
## When to use nx_docs
|
||||
|
||||
- USE for: advanced config options, unfamiliar flags, migration guides, plugin configuration, edge
|
||||
cases
|
||||
- DON'T USE for: basic generator syntax (`nx g @nx/react:app`), standard commands, things you
|
||||
already know
|
||||
- The `nx-generate` skill handles generator discovery internally - don't call nx_docs just to look
|
||||
up generator syntax
|
||||
|
||||
<!-- nx configuration end-->
|
||||
@@ -0,0 +1,131 @@
|
||||
# Nx-монорепозиторий — шаблон
|
||||
|
||||
Стартовый репозиторий для нового веб-проекта: Nx 22 + yarn workspaces, бэкенд на NestJS с TypeORM и
|
||||
PostgreSQL, фронтенд на React + Vite, e2e-тесты, единый линт, миграции, CI/CD в Gitea Actions со
|
||||
стендом на каждую ветку и документация в MDX.
|
||||
|
||||
Шаблон содержит пустой каркас приложений (health-check и демо-страница) и полностью рабочую
|
||||
инфраструктуру: сборку, миграции, проверки, деплой и документацию. Новый проект начинается с
|
||||
клонирования репозитория и чек-листа из раздела «Новый проект из шаблона».
|
||||
|
||||
## Что уже настроено
|
||||
|
||||
- **Монорепозиторий.** Nx 22 управляет задачами, yarn workspaces — зависимостями приложений и
|
||||
пакетов; общие библиотеки добавляются в `packages/`.
|
||||
- **Приложения.** `api` (NestJS 11, глобальный префикс `/api`, Swagger на `/api/docs`), `web` (React
|
||||
19 + Vite 7 + Tailwind, раздача статики через Caddy), `api-e2e` (Jest).
|
||||
- **Линт и форматирование.** ESLint flat config, Prettier, Stylelint, `tsc --noEmit`; одна команда
|
||||
`yarn lint` чинит, `yarn lint:check` — проверяет как в CI.
|
||||
- **Хуки git.** Husky запускает `lint-staged` на pre-commit и проверку имени ветки на pre-push.
|
||||
- **Миграции TypeORM.** Статический список миграций генерируется скриптом (webpack не умеет
|
||||
runtime-glob), есть снимок данных БД в JSON и восстановление из снимка.
|
||||
- **CI/CD.** Gitea Actions: ветка → Docker-образы + стенд, удаление ветки → удаление стенда, тег
|
||||
`v*` → прод. Деплой применяет миграции автоматически.
|
||||
- **Документация.** MDX в `docs/`, публикуется через Docuservix.
|
||||
- **Шаблоны задач.** `bug`, `issue`, `epic`, `user-story` в `.gitea/issue_template/`.
|
||||
- **Инструкции для ИИ-агентов.** `AGENTS.md` — обзор, команды, архитектура и конвенции; плюс конфиги
|
||||
для Cursor, GitHub Copilot, Gemini, Codex, OpenCode.
|
||||
|
||||
## Стек
|
||||
|
||||
| Слой | Технологии |
|
||||
| -------- | --------------------------------------------------- |
|
||||
| Сборка | Nx 22, yarn 1 (workspaces), TypeScript 5.9, Node 24 |
|
||||
| Бэкенд | NestJS 11, TypeORM, PostgreSQL, webpack, Vitest |
|
||||
| Фронтенд | React 19, Vite 7, Tailwind, Caddy |
|
||||
| E2E | Jest |
|
||||
| Качество | ESLint, Prettier, Stylelint, Husky, lint-staged |
|
||||
| Доставка | Gitea Actions, Docker, docker compose, Docuservix |
|
||||
|
||||
## Структура
|
||||
|
||||
| Путь | Назначение |
|
||||
| ------------------------ | ----------------------------------------------------------------------------- |
|
||||
| `apps/api` | NestJS-бэкенд: TypeORM + PostgreSQL, сборка webpack, тесты Vitest |
|
||||
| `apps/web` | React + Vite + Tailwind, Caddy раздаёт статику и проксирует `/api` |
|
||||
| `apps/api-e2e` | e2e-тесты API на Jest |
|
||||
| `packages/` | общие библиотеки воркспейса |
|
||||
| `tools/` | скрипты воркспейса: сборка и проверка data source, снимок и восстановление БД |
|
||||
| `docs/` | документация в MDX: слои приложений, БД, логирование, деплой |
|
||||
| `.gitea/workflows/` | CI/CD: `ci.yaml` (ветки), `production.yaml` (теги), `cleanup.yaml` |
|
||||
| `.gitea/issue_template/` | шаблоны задач Gitea |
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
```bash
|
||||
yarn install
|
||||
yarn start # api на :5000 (Swagger — /api/docs), web на :5173
|
||||
```
|
||||
|
||||
Проверить, что всё поднялось: `http://localhost:5000/api/health` и `http://localhost:5173`. Задачи
|
||||
запускаются только через Nx:
|
||||
|
||||
```bash
|
||||
yarn nx run <project>:<target> # одна задача
|
||||
yarn nx run-many -t <target> # по всем проектам
|
||||
yarn nx affected -t <target> # только по затронутым проектам
|
||||
```
|
||||
|
||||
## Команды
|
||||
|
||||
| Команда | Что делает |
|
||||
| -------------------------------------- | ------------------------------------------------------ |
|
||||
| `yarn start` | запуск всех приложений |
|
||||
| `yarn build` | сборка всех проектов |
|
||||
| `yarn rebuild` | очистка и сборка заново |
|
||||
| `yarn lint` | линт с автофиксом: eslint + prettier + stylelint + tsc |
|
||||
| `yarn lint:check` | те же проверки без автофикса (используется в CI) |
|
||||
| `yarn db-show` | статус миграций TypeORM |
|
||||
| `yarn db-migrate` / `yarn db-revert` | применить непримененные / откатить последнюю миграцию |
|
||||
| `yarn db-migrations-list` | перегенерировать статический список миграций |
|
||||
| `yarn db-snapshot` / `yarn db-restore` | снимок данных БД в JSON и восстановление из снимка |
|
||||
|
||||
Подключение к БД задаётся переменными `POSTGRES_HOST`, `POSTGRES_PORT`, `POSTGRES_USER`,
|
||||
`POSTGRES_PASSWORD`, `POSTGRES_DB` — в `.env` локально или в окружении контейнера.
|
||||
|
||||
## Ветки и пайплайны
|
||||
|
||||
- `master` — основная ветка.
|
||||
- Рабочие ветки — `i<номер>-краткое-описание`, только `a-z`, `0-9` и `-`; формат проверяют Husky на
|
||||
pre-push и CI.
|
||||
- Пуш в ветку или PR: сборка, проверка имени ветки, проверка списка миграций, сборка Docker-образов
|
||||
`api`/`web`, стенд на `<ветка>.<домен>`, линт, публикация документации.
|
||||
- Удаление ветки: стенд удаляется (`cleanup.yaml`).
|
||||
- Тег `v*`: сборка и выкладка в прод (`production.yaml`), миграции применяются автоматически.
|
||||
|
||||
## Новый проект из шаблона
|
||||
|
||||
1. **Переименовать воркспейс.** `package.json` (`@it-smi/*`), `project.json`, `nx.json`,
|
||||
`tsconfig.base.json` (`paths` и `customConditions`), `apps/*/package.json`.
|
||||
2. **Настроить доставку.** Домен и registry в `.gitea/workflows/*.yaml`,
|
||||
`docker-compose.production.yml`, `docker-compose.staging.yml`, `.docuservix.yml`; домен в
|
||||
`apps/web/Caddyfile` и список CORS-origin в `apps/api/src/main.ts`.
|
||||
3. **Задать переменные и секреты репозитория в Gitea.** `vars.REGISTRY_USER`, `vars.STAGING_HOST`,
|
||||
`vars.STAGING_USER`, `vars.STAGING_PORT`; `secrets.REGISTRY_PASSWORD`,
|
||||
`secrets.STAGING_SSH_PRIVATE_KEY`.
|
||||
4. **Убрать демо-код.** `apps/web/src/app/nx-welcome.tsx` и демо-страница в `apps/web/src/app`,
|
||||
тестовый контроллер и сервис в `apps/api/src/app`.
|
||||
5. **Пересобрать миграции.** Удалить тестовую миграцию из `apps/api/src/database/migrations/` и
|
||||
выполнить `yarn db-migrations-list`; список `apps/api/src/migrations.ts` коммитится.
|
||||
6. **Обновить тексты под проект.** `docs/index.md`, документы в `docs/`, `AGENTS.md`, этот
|
||||
`README.md`.
|
||||
7. **Проверить ветку в CI.** Первый пуш должен пройти `yarn lint:check` и сборку, а стенд —
|
||||
открыться по своему адресу.
|
||||
|
||||
## Документация
|
||||
|
||||
- [Оглавление](docs/index.md)
|
||||
- [Слои API](docs/50-developing/01-api-layers.md) и [слои web](docs/50-developing/02-web-layers.md)
|
||||
- [Работа с БД](docs/50-developing/10-persistence.md),
|
||||
[миграции](docs/50-developing/20-migrations.md),
|
||||
[доступ к данным](docs/50-developing/30-data-access.md), [тесты](docs/50-developing/40-testing.md)
|
||||
- [Ручное логирование](docs/55-logging/04-manual-logs.md)
|
||||
- [Миграции и деплой](docs/90-deploy/10-migrations.md)
|
||||
|
||||
Инструкции для ИИ-агентов (в том числе Claude Code) — в [AGENTS.md](AGENTS.md).
|
||||
|
||||
## Полезные ссылки
|
||||
|
||||
- [Документация Nx](https://nx.dev/getting-started/intro)
|
||||
- [Запуск задач в Nx](https://nx.dev/features/run-tasks)
|
||||
- [Nx Console](https://nx.dev/getting-started/editor-setup)
|
||||
Whitespace-only changes.
@@ -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": []
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import baseConfig from '../../eslint.config.mjs';
|
||||
|
||||
export default [...baseConfig];
|
||||
@@ -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',
|
||||
};
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "@it-smi/api-e2e",
|
||||
"version": "0.0.1",
|
||||
"private": true
|
||||
}
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import axios from 'axios';
|
||||
import { describe, expect, 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' });
|
||||
});
|
||||
});
|
||||
@@ -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__);
|
||||
};
|
||||
@@ -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}`;
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "out-tsc/@it-smi/api-e2e",
|
||||
"esModuleInterop": true,
|
||||
"noUnusedLocals": false,
|
||||
"noImplicitAny": false
|
||||
},
|
||||
"include": [
|
||||
"jest.config.ts",
|
||||
"src/**/*.ts"
|
||||
],
|
||||
"references": []
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
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
|
||||
# Прод-режим по умолчанию: JSON-логи pino и никаких pino-pretty из devDependencies,
|
||||
# которые в образ не попадают. Переопределяется через docker-compose при необходимости.
|
||||
ENV PORT=5000
|
||||
ENV NODE_ENV=production
|
||||
|
||||
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"]
|
||||
@@ -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) {
|
||||
// Массив строк-префиксов, например ['@it-smi/']
|
||||
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');
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,3 @@
|
||||
import baseConfig from '../../eslint.config.mjs';
|
||||
|
||||
export default [...baseConfig];
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@it-smi/api",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^11.0.0",
|
||||
"@nestjs/core": "^11.0.0",
|
||||
"@nestjs/platform-express": "^11.0.0",
|
||||
"@nestjs/swagger": "^11.4.7",
|
||||
"@nestjs/terminus": "^11.1.1",
|
||||
"@nestjs/typeorm": "^11.0.0",
|
||||
"axios": "^1.6.0",
|
||||
"colorette": "^2.0.20",
|
||||
"dotenv": "^16.4.7",
|
||||
"nestjs-pino": "^4.4.1",
|
||||
"pg": "^8.20.0",
|
||||
"pino": "^9.11.0",
|
||||
"pino-http": "^10.5.0",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rxjs": "^7.8.0",
|
||||
"typeorm": "^0.3.31"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/schematics": "^11.0.0",
|
||||
"@nestjs/testing": "^11.0.0",
|
||||
"pino-pretty": "^13.1.1",
|
||||
"webpack-cli": "^5.1.4"
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Module, OnModuleDestroy } from '@nestjs/common';
|
||||
|
||||
import { DatabaseModule } from '../database/database.module';
|
||||
import { HealthModule } from '../health/health.module';
|
||||
import { LocalLoggerModule, Logger } from '../logger';
|
||||
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
@Module({
|
||||
imports: [LocalLoggerModule.forRoot(), DatabaseModule, HealthModule],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
})
|
||||
export class AppModule implements OnModuleDestroy {
|
||||
onModuleDestroy() {
|
||||
new Logger('AppModule').warn('Backend is shutting down');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class AppService {
|
||||
getData(): { message: string } {
|
||||
return { message: 'Hello API' };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import * as path from 'path';
|
||||
|
||||
import { config } from 'dotenv';
|
||||
import { DataSource } from 'typeorm';
|
||||
|
||||
import { migrations } from '../migrations';
|
||||
|
||||
// Загружаем env файлы в правильном порядке.
|
||||
// Внутри контейнера файлов нет — dotenv молча пропустит их, значения берутся из окружения.
|
||||
const nodeEnv = process.env.NODE_ENV || 'production';
|
||||
config({ path: path.resolve(process.cwd(), `.env.${nodeEnv}`) });
|
||||
config({ path: path.resolve(process.cwd(), '.env') });
|
||||
|
||||
// entities нужны только CLI и только при запуске из TS-исходников
|
||||
// (migration:generate, schema:drop). Путь привязан к самому файлу, а не к
|
||||
// process.cwd(): cwd-относительный glob при запуске из другой директории молча
|
||||
// резолвится в пустой список, и migration:generate тогда генерирует миграцию,
|
||||
// удаляющую все таблицы, а schema:drop превращается в no-op.
|
||||
// В собранном бандле (__dirname === /app) тот же glob ушёл бы сканировать корень
|
||||
// файловой системы, поэтому там список пустой — на migration:run он не влияет.
|
||||
const isTypeScriptRuntime = __filename.endsWith('.ts');
|
||||
const entities = isTypeScriptRuntime ? [path.join(__dirname, '..', '**', '*.entity.ts')] : [];
|
||||
|
||||
const AppDataSource = new DataSource({
|
||||
type: 'postgres',
|
||||
username: process.env.POSTGRES_USER,
|
||||
password: process.env.POSTGRES_PASSWORD,
|
||||
database: process.env.POSTGRES_DB,
|
||||
host: process.env.POSTGRES_HOST,
|
||||
port: +(process.env.POSTGRES_PORT || 5432),
|
||||
synchronize: false,
|
||||
entities,
|
||||
// Статический список — webpack не умеет runtime-glob (tools/buildDataSource.ts).
|
||||
migrations,
|
||||
migrationsRun: false,
|
||||
logging: true,
|
||||
});
|
||||
|
||||
export default AppDataSource;
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
|
||||
import AppDataSource from '../config/typeorm.config';
|
||||
|
||||
/**
|
||||
* Подключение приложения к БД.
|
||||
*
|
||||
* Настройки берутся из того же `typeorm.config.ts`, что использует CLI миграций:
|
||||
* там же загружаются env-файлы, поэтому приложению не нужен второй набор
|
||||
* переменных окружения. Сущности модулей подключаются через
|
||||
* `TypeOrmModule.forFeature` (autoLoadEntities), статический список `entities`
|
||||
* остаётся нужен только CLI.
|
||||
*
|
||||
* Собственный логгер TypeORM выключен: логи приложения идут через pino
|
||||
* (docs/55-logging), иначе SQL-запросы печатаются мимо него.
|
||||
*/
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forRoot({
|
||||
...AppDataSource.options,
|
||||
autoLoadEntities: true,
|
||||
logging: false,
|
||||
migrationsRun: false,
|
||||
}),
|
||||
],
|
||||
})
|
||||
export class DatabaseModule {}
|
||||
Whitespace-only changes.
@@ -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__,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TerminusModule } from '@nestjs/terminus';
|
||||
|
||||
import { HealthController } from './health.controller';
|
||||
|
||||
@Module({
|
||||
imports: [TerminusModule],
|
||||
controllers: [HealthController],
|
||||
})
|
||||
export class HealthModule {}
|
||||
@@ -0,0 +1,36 @@
|
||||
import pino, { Logger as PinoLogger } from 'pino';
|
||||
import type { PrettyOptions } from 'pino-pretty';
|
||||
|
||||
/**
|
||||
* В продакшене пишем машиночитаемый JSON, в остальных окружениях — человекочитаемый вывод.
|
||||
* LOG_PRETTY явно перекрывает определение по NODE_ENV (нужно, когда образ собран под прод,
|
||||
* а контейнер поднят локально).
|
||||
*/
|
||||
const isProduction = process.env.NODE_ENV === 'production' || process.env.LOG_PRETTY === 'false';
|
||||
|
||||
const baseLogger = pino({
|
||||
level: process.env.LOG_LEVEL ?? (isProduction ? 'info' : 'debug'),
|
||||
transport: isProduction
|
||||
? undefined
|
||||
: {
|
||||
target: 'pino-pretty',
|
||||
options: {
|
||||
colorize: true,
|
||||
translateTime: 'HH:MM:ss.l',
|
||||
ignore: 'pid,hostname,context,reqId,res,url,statusCode,responseTime',
|
||||
messageFormat: [
|
||||
'\x1b[36m{reqId}\x1b[0m',
|
||||
'\x1b[33m{context}\x1b[0m',
|
||||
'\x1b[34m{msg}\x1b[0m',
|
||||
].join(' '),
|
||||
} as PrettyOptions,
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Единственный экземпляр pino на процесс: и корневой логгер приложения, и pino-http
|
||||
* пишут через него, поэтому транспорт (воркер pino-pretty) создаётся один раз.
|
||||
*/
|
||||
export function getBaseLogger(): PinoLogger {
|
||||
return baseLogger;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from './base';
|
||||
export * from './logger.class';
|
||||
export * from './logger.module';
|
||||
@@ -0,0 +1,167 @@
|
||||
import { Inject, Injectable, LoggerService, Scope } from '@nestjs/common';
|
||||
import { PinoLogger } from 'nestjs-pino';
|
||||
import { Bindings } from 'pino';
|
||||
|
||||
import { getBaseLogger } from './base';
|
||||
|
||||
export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
|
||||
|
||||
@Injectable({ scope: Scope.TRANSIENT })
|
||||
export class Logger implements LoggerService {
|
||||
private readonly logger: PinoLogger;
|
||||
|
||||
constructor();
|
||||
constructor(context: string);
|
||||
constructor(
|
||||
@Inject(PinoLogger)
|
||||
context?: string | PinoLogger,
|
||||
) {
|
||||
if (context && context instanceof PinoLogger) {
|
||||
this.logger = context;
|
||||
} else {
|
||||
const bindings: Bindings = context ? { context } : {};
|
||||
|
||||
this.logger = getBaseLogger().child(bindings) as unknown as PinoLogger;
|
||||
}
|
||||
}
|
||||
|
||||
setContext(context: string) {
|
||||
if (this.logger instanceof PinoLogger) {
|
||||
this.logger.setContext(context);
|
||||
} else {
|
||||
throw new Error('Cannot set context on child logger');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Трассировка, максимальная детализация
|
||||
*
|
||||
* Log level: 10
|
||||
*
|
||||
* Самый подробный уровень. Используется для сложных расследований и поиска причин ошибок.
|
||||
*
|
||||
* Примеры:
|
||||
* - пошаговое логирование алгоритма
|
||||
* - шаги в обработке запроса
|
||||
* - переходы между этапами обработки
|
||||
* - детали бизнес-логики
|
||||
*/
|
||||
trace(message: string, details?: object) {
|
||||
this.logInner('trace', message, details);
|
||||
}
|
||||
|
||||
/**
|
||||
* Отладка, подробности бизнес-логики
|
||||
*
|
||||
* Log level: 20
|
||||
*
|
||||
* Сообщения для разработчиков, полезные при разборе логики работы.
|
||||
*
|
||||
* Примеры:
|
||||
* - запрос разрешений
|
||||
* - ключевые шаги алгоритма
|
||||
* - получение данных из внешних сервисов
|
||||
* - события жизненного цикла приложения
|
||||
* - ответы от внешних сервисов
|
||||
*/
|
||||
debug(message: string, details?: object) {
|
||||
this.logInner('debug', message, details);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ключевые события приложения
|
||||
*
|
||||
* Log level: 30
|
||||
*
|
||||
* Информационные сообщения о нормальной работе приложения.
|
||||
*
|
||||
* Примеры:
|
||||
* - запрос к API
|
||||
* - пользователь успешно вошёл в систему
|
||||
* - заявка создана
|
||||
* - бизнес-операция успешно выполнена
|
||||
*/
|
||||
log(message: string, details?: object) {
|
||||
this.logInner('info', message, details);
|
||||
}
|
||||
|
||||
/**
|
||||
* Потенциальная проблема, нестандартное поведение
|
||||
*
|
||||
* Log level: 40
|
||||
*
|
||||
* Предупреждения о нежелательных или подозрительных ситуациях, которые не приводят к немедленной поломке.
|
||||
*
|
||||
* Примеры:
|
||||
* - потенциально опасное поведение пользователя
|
||||
* - использование устаревшего API
|
||||
* - медленный запрос
|
||||
*/
|
||||
warn(message: string, details?: object) {
|
||||
this.logInner('warn', message, details);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ошибка, требующая реакции
|
||||
*
|
||||
* Log level: 50
|
||||
*
|
||||
* Серьёзные ошибки в работе приложения, которые нужно обрабатывать.
|
||||
*
|
||||
* Примеры:
|
||||
* - API отдало 500
|
||||
* - не удалось выполнить бизнес-операцию.
|
||||
*/
|
||||
error(message: string, details?: object): void;
|
||||
/**
|
||||
* Ошибка, требующая реакции
|
||||
*
|
||||
* Log level: 50
|
||||
*
|
||||
* Серьёзные ошибки в работе приложения, которые нужно обрабатывать.
|
||||
*
|
||||
* Примеры:
|
||||
* - API отдало 500
|
||||
* - не удалось выполнить бизнес-операцию.
|
||||
*/
|
||||
error(message: string, trace?: string, details?: object): void;
|
||||
error(message: string, traceOrDetails?: string | object, details?: object | string) {
|
||||
if (typeof details === 'string') {
|
||||
details = { context: details };
|
||||
}
|
||||
|
||||
if (typeof traceOrDetails === 'string') {
|
||||
details = { ...details, trace: traceOrDetails };
|
||||
}
|
||||
|
||||
this.logInner('error', message, details);
|
||||
}
|
||||
|
||||
/**
|
||||
* Критическая ошибка, завершение работы
|
||||
*
|
||||
* Log level: 60
|
||||
*
|
||||
* Используется для ситуаций, после которых приложение не может продолжать работу.
|
||||
*
|
||||
* Примеры:
|
||||
* - падение основного процесса
|
||||
* - невозможность поднять сервер на указанном порту
|
||||
* - не корректная конфигурация
|
||||
* - не удалось подключиться к базе данных
|
||||
*/
|
||||
fatal(message: string, details?: object) {
|
||||
this.logInner('fatal', message, details);
|
||||
}
|
||||
|
||||
protected logInner(level: LogLevel, message: string, details?: object | string) {
|
||||
if (typeof details === 'object' && details !== null) {
|
||||
this.logger[level](details, message);
|
||||
} else if (typeof details === 'string') {
|
||||
// Для совместимости с логгером по умолчанию в NestJS
|
||||
this.logger[level]({ context: details }, message);
|
||||
} else {
|
||||
this.logger[level](message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { IncomingMessage, ServerResponse } from 'http';
|
||||
|
||||
import { DynamicModule, INestApplication, Module } from '@nestjs/common';
|
||||
import { LoggerModule, PinoLogger } from 'nestjs-pino';
|
||||
|
||||
import { getBaseLogger } from './base';
|
||||
import { Logger } from './logger.class';
|
||||
import { MockLogger, TestingLogger } from './testing';
|
||||
|
||||
@Module({})
|
||||
export class LocalLoggerModule {
|
||||
/**
|
||||
* Рабочая конфигурация: наш pino (base.ts) + автоматические HTTP-логи через pino-http.
|
||||
*/
|
||||
public static forRoot(): DynamicModule {
|
||||
return {
|
||||
global: true,
|
||||
module: LocalLoggerModule,
|
||||
imports: [
|
||||
LoggerModule.forRoot({
|
||||
pinoHttp: {
|
||||
// важное место: используем наш СУЩЕСТВУЮЩИЙ pino, а не создаём новый
|
||||
logger: getBaseLogger(),
|
||||
|
||||
autoLogging: true,
|
||||
|
||||
customProps: (req: IncomingMessage) => ({
|
||||
url: req.method + ' ' + req.url,
|
||||
context: 'HTTP',
|
||||
}),
|
||||
quietReqLogger: true,
|
||||
quietResLogger: true,
|
||||
|
||||
customLogLevel: function (
|
||||
_req: IncomingMessage,
|
||||
res: ServerResponse,
|
||||
err?: Error,
|
||||
) {
|
||||
if (res.statusCode >= 500 || err) {
|
||||
return 'error';
|
||||
} else if (res.statusCode >= 300 && res.statusCode < 400) {
|
||||
return 'silent';
|
||||
}
|
||||
|
||||
return 'info';
|
||||
},
|
||||
customSuccessMessage(req: IncomingMessage, res: ServerResponse) {
|
||||
return `Request completed: ${res.statusCode} ${req.method} ${req.url}`;
|
||||
},
|
||||
customSuccessObject(
|
||||
_req: IncomingMessage,
|
||||
res: ServerResponse,
|
||||
val: { responseTime: number },
|
||||
) {
|
||||
return {
|
||||
statusCode: res.statusCode,
|
||||
responseTime: val.responseTime,
|
||||
};
|
||||
},
|
||||
customErrorMessage(req: IncomingMessage, res: ServerResponse, err: Error) {
|
||||
return `Request error: ${res.statusCode} ${req.method} ${req.url} ${err.message}`;
|
||||
},
|
||||
customErrorObject(
|
||||
req: IncomingMessage,
|
||||
res: ServerResponse,
|
||||
_err: Error,
|
||||
val: { responseTime: number },
|
||||
) {
|
||||
return {
|
||||
url: req.method + ' ' + req.url,
|
||||
statusCode: res.statusCode,
|
||||
responseTime: val.responseTime,
|
||||
};
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
providers: [Logger],
|
||||
exports: [Logger],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Конфигурация для тестов: логи складываются в память и проверяются через TestingLogger.
|
||||
*/
|
||||
public static forTesting(): DynamicModule {
|
||||
return {
|
||||
global: true,
|
||||
module: LocalLoggerModule,
|
||||
providers: [
|
||||
TestingLogger,
|
||||
{
|
||||
provide: Logger,
|
||||
useFactory: (testingLogger: TestingLogger) => new MockLogger(testingLogger),
|
||||
inject: [TestingLogger],
|
||||
},
|
||||
{
|
||||
provide: PinoLogger,
|
||||
useValue: {},
|
||||
},
|
||||
],
|
||||
exports: [Logger, TestingLogger],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Подмена логгера Nest нашим. Вызывать после NestFactory.create с bufferLogs: true —
|
||||
* useLogger сбрасывает буфер в наш логгер.
|
||||
*/
|
||||
public static setup(app: INestApplication) {
|
||||
app.useLogger(new Logger());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './logger.class';
|
||||
export * from './testing-logger.class';
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Logger, LogLevel } from '../logger.class';
|
||||
|
||||
import { TestingLogger } from './testing-logger.class';
|
||||
|
||||
export class MockLogger extends Logger {
|
||||
private context: string;
|
||||
|
||||
constructor(private readonly testingLogger: TestingLogger) {
|
||||
super();
|
||||
}
|
||||
|
||||
override setContext(context: string) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
protected override logInner(level: LogLevel, message: string, details?: object) {
|
||||
this.testingLogger.log(level, message, this.context, details);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
import * as colorette from 'colorette';
|
||||
|
||||
import { LogLevel } from '../logger.class';
|
||||
|
||||
import { fail, LogEntry, PrettifyStackTrace, showLogDetails, showLogObject } from './utils';
|
||||
|
||||
export type { LogEntry };
|
||||
|
||||
export class TestingLogger {
|
||||
private readonly entries: LogEntry[] = [];
|
||||
|
||||
/**
|
||||
* Добавление записи лога
|
||||
*/
|
||||
log(level: LogLevel, message: string, context: string, details?: object) {
|
||||
this.entries.push({
|
||||
level,
|
||||
message,
|
||||
context,
|
||||
...details,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Очистка всех записей логов
|
||||
*/
|
||||
clear() {
|
||||
this.entries.length = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Любые логи (старт без фильтра)
|
||||
*/
|
||||
any(): TestingLoggerMatcher {
|
||||
return new TestingLoggerMatcher(this.entries, {});
|
||||
}
|
||||
|
||||
/**
|
||||
* Старт от фильтра по сообщению
|
||||
*/
|
||||
withMessage(message: string): TestingLoggerMatcher {
|
||||
return new TestingLoggerMatcher(this.entries, { message });
|
||||
}
|
||||
|
||||
/**
|
||||
* Старт от фильтра по уровню
|
||||
*/
|
||||
withLevel(level: LogLevel): TestingLoggerMatcher {
|
||||
return new TestingLoggerMatcher(this.entries, { level });
|
||||
}
|
||||
|
||||
/**
|
||||
* Старт от фильтра по контексту
|
||||
*/
|
||||
withContext(context: string): TestingLoggerMatcher {
|
||||
return new TestingLoggerMatcher(this.entries, { context });
|
||||
}
|
||||
}
|
||||
|
||||
const BASE_FIELDS: (keyof LogEntry)[] = ['level', 'message', 'context'];
|
||||
|
||||
export class TestingLoggerMatcher {
|
||||
constructor(
|
||||
private readonly entries: LogEntry[],
|
||||
private readonly filter: Partial<LogEntry>,
|
||||
private readonly strict = false,
|
||||
) {}
|
||||
|
||||
get logs() {
|
||||
// В режиме strict мы хотим строгое совпадение деталей: все ключи деталей должны совпадать
|
||||
// и не должно быть лишних ключей деталей у записи.
|
||||
if (this.strict) {
|
||||
return this.entries.filter((log) => {
|
||||
// проверяем базовые поля, если они заданы в фильтре
|
||||
for (const field of BASE_FIELDS) {
|
||||
if (this.filter[field] !== undefined && log[field] !== this.filter[field]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ключи деталей в фильтре и в самой записи
|
||||
const detailFilterKeys = Object.keys(this.filter).filter((k) => {
|
||||
return !BASE_FIELDS.includes(k as keyof LogEntry);
|
||||
});
|
||||
const entryDetailKeys = Object.keys(log).filter((k) => {
|
||||
return !BASE_FIELDS.includes(k as keyof LogEntry);
|
||||
});
|
||||
|
||||
// размеры наборов деталей должны совпадать
|
||||
if (detailFilterKeys.length !== entryDetailKeys.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// все ключи из фильтра должны присутствовать и иметь одинаковые значения
|
||||
return detailFilterKeys.every((key) => {
|
||||
return log[key] === this.filter[key];
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return this.entries.filter((log) => {
|
||||
for (const key in this.filter) {
|
||||
if (log[key] !== this.filter[key]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
showLogs(options: { hideFilter?: boolean; logs?: LogEntry[] } = {}): this {
|
||||
const { hideFilter = false, logs = this.logs } = options;
|
||||
|
||||
process.stdout.write(colorette.bold(colorette.white('--- Logs ---')) + '\n');
|
||||
|
||||
if (!hideFilter) {
|
||||
process.stdout.write(colorette.bold(colorette.cyan('Filter:')) + '\n');
|
||||
|
||||
if (Object.keys(this.filter).length === 0) {
|
||||
process.stdout.write(' (no filter, showing all logs)\n');
|
||||
} else {
|
||||
showLogDetails({
|
||||
level: this.filter.level,
|
||||
context: this.filter.context,
|
||||
message: this.filter.message,
|
||||
...this.filter,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
process.stdout.write(colorette.bold(colorette.white('Found logs:')) + '\n');
|
||||
|
||||
logs.forEach((log) => {
|
||||
showLogObject(log);
|
||||
process.stdout.write('\n'); // пустая строка между логами
|
||||
});
|
||||
|
||||
process.stdout.write(` Found ${logs.length} log(s) total\n\n`);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Фильтр по сообщению
|
||||
*/
|
||||
withMessage(message: string): TestingLoggerMatcher {
|
||||
return new TestingLoggerMatcher(this.entries, { ...this.filter, message }, this.strict);
|
||||
}
|
||||
|
||||
/**
|
||||
* Фильтр по уровню
|
||||
*/
|
||||
withLevel(level: LogLevel): TestingLoggerMatcher {
|
||||
return new TestingLoggerMatcher(this.entries, { ...this.filter, level }, this.strict);
|
||||
}
|
||||
|
||||
/**
|
||||
* Фильтр по контексту
|
||||
*/
|
||||
withContext(context: string): TestingLoggerMatcher {
|
||||
return new TestingLoggerMatcher(this.entries, { ...this.filter, context }, this.strict);
|
||||
}
|
||||
|
||||
/**
|
||||
* Фильтр по дополнительным деталям
|
||||
*/
|
||||
withDetails(obj: Record<string, boolean | number | string>): TestingLoggerMatcher {
|
||||
return new TestingLoggerMatcher(this.entries, { ...this.filter, ...obj }, this.strict);
|
||||
}
|
||||
|
||||
/**
|
||||
* Фильтр по дополнительным деталям - строгий (все детали должны совпадать, лишних быть не должно)
|
||||
*/
|
||||
strictDetails(): TestingLoggerMatcher {
|
||||
return new TestingLoggerMatcher(this.entries, { ...this.filter }, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка наличия логов
|
||||
*/
|
||||
@PrettifyStackTrace()
|
||||
toBeLogged(): void {
|
||||
if (this.logs.length === 0) {
|
||||
if (this.entries.length) {
|
||||
this.toBeLoggedTimes(1);
|
||||
} else {
|
||||
return fail('No logs recorded');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка отсутствия логов
|
||||
*/
|
||||
@PrettifyStackTrace()
|
||||
toBeNotLogged(): void {
|
||||
this.toBeLoggedTimes(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка, что лог был записан ровно один раз
|
||||
*/
|
||||
@PrettifyStackTrace()
|
||||
toBeLoggedOnce(): void {
|
||||
this.toBeLoggedTimes(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка, что лог был записан ровно n раз
|
||||
*/
|
||||
@PrettifyStackTrace()
|
||||
toBeLoggedTimes(n: number): void {
|
||||
if (this.logs.length === n) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.throwDiff(n);
|
||||
}
|
||||
|
||||
private throwDiff(n: number) {
|
||||
if (!this.entries.length) {
|
||||
return fail('No logs recorded');
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
[
|
||||
`Expected ${n} log(s)` + describedFilter(this.filter),
|
||||
this.logs.length ? '\nFound:' : '',
|
||||
...this.logs.map((entry) => ` ${logEntryToString(this.filter)(entry)}`),
|
||||
this.logs.length ? '' : ' (none)',
|
||||
].join('\n'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function describedFilter(filter: Partial<LogEntry>): string {
|
||||
const keys = Object.keys(filter);
|
||||
|
||||
if (!keys.length) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return ` matching ${keys.map((key) => `${key}=${String(filter[key])}`).join(', ')}`;
|
||||
}
|
||||
|
||||
function logEntryToString(filter: Partial<LogEntry>) {
|
||||
return (entry: LogEntry): string => {
|
||||
let result = '';
|
||||
|
||||
if (filter.context) {
|
||||
result += `${entry.context} `;
|
||||
}
|
||||
|
||||
if (filter.level) {
|
||||
result += `[${entry.level}] `;
|
||||
}
|
||||
|
||||
if (filter.message) {
|
||||
result += `${entry.message}`;
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,567 @@
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { Logger } from '../logger.class';
|
||||
import { LocalLoggerModule } from '../logger.module';
|
||||
|
||||
import { TestingLogger } from './testing-logger.class';
|
||||
|
||||
describe('TestingLogger', () => {
|
||||
let mockLogger: Logger;
|
||||
let logger: TestingLogger;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module = await Test.createTestingModule({
|
||||
imports: [LocalLoggerModule.forTesting()],
|
||||
}).compile();
|
||||
|
||||
mockLogger = await module.resolve(Logger);
|
||||
logger = module.get(TestingLogger);
|
||||
});
|
||||
|
||||
it('complex test', () => {
|
||||
// Arrange
|
||||
mockLogger.setContext('RBAC');
|
||||
|
||||
// Act
|
||||
mockLogger.debug('Access granted', { user: 1, permissions: ['read'] });
|
||||
mockLogger.log('Access granted', { user: 2, permissions: ['read', 'write'] });
|
||||
mockLogger.warn('Access denied', { user: 1 });
|
||||
mockLogger.log('User logged in', { user: 1 });
|
||||
mockLogger.error('Unexpected error', { error: new Error('Test error') });
|
||||
|
||||
// Assert
|
||||
const rbacLogger = logger.withContext('RBAC');
|
||||
|
||||
rbacLogger.withMessage('Access denied').toBeLogged();
|
||||
|
||||
rbacLogger.withMessage('Access granted').withLevel('debug').toBeLogged();
|
||||
rbacLogger.withMessage('Access granted').withLevel('info').toBeLogged();
|
||||
rbacLogger.withMessage('User logged in').withLevel('info').toBeLogged();
|
||||
rbacLogger.withMessage('Unexpected error').withLevel('error').toBeLogged();
|
||||
|
||||
rbacLogger.toBeLoggedTimes(5);
|
||||
|
||||
rbacLogger.withMessage('Access granted').toBeLoggedTimes(2);
|
||||
rbacLogger.withMessage('Access denied').toBeLoggedOnce();
|
||||
rbacLogger.withMessage('User logged in').toBeLoggedOnce();
|
||||
rbacLogger.withMessage('Unexpected error').toBeLoggedOnce();
|
||||
|
||||
rbacLogger.withMessage('Access granted').withDetails({ user: 1 }).toBeLoggedOnce();
|
||||
});
|
||||
|
||||
describe('TestingLogger — базовые операции', () => {
|
||||
it('сохраняет запись через log() (все поля + details)', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'msg', 'CTX', { a: 1 });
|
||||
|
||||
// Act
|
||||
const matcher = logger.any();
|
||||
|
||||
// Assert
|
||||
matcher.toBeLoggedOnce();
|
||||
// Проверяем точное соответствие
|
||||
const entries = matcher.logs;
|
||||
|
||||
expect(entries[0]).toEqual({
|
||||
level: 'info',
|
||||
message: 'msg',
|
||||
context: 'CTX',
|
||||
a: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('log() без details не добавляет лишних ключей', () => {
|
||||
// Arrange
|
||||
logger.log('warn', 'msg', 'CTX');
|
||||
|
||||
// Act
|
||||
const matcher = logger.any();
|
||||
|
||||
matcher.toBeLoggedOnce();
|
||||
const entry = matcher.logs[0];
|
||||
|
||||
// Assert
|
||||
expect(entry).toEqual({
|
||||
level: 'warn',
|
||||
message: 'msg',
|
||||
context: 'CTX',
|
||||
});
|
||||
// Проверяем отсутствие произвольных ключей
|
||||
expect(entry.a).toBeUndefined();
|
||||
expect(entry.b).toBeUndefined();
|
||||
});
|
||||
|
||||
it('поля из details перекрывают базовые при совпадении ключей', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'base', 'CTX', {
|
||||
message: 'override',
|
||||
level: 'error',
|
||||
context: 'OVR',
|
||||
});
|
||||
|
||||
// Act
|
||||
const matcher = logger.any();
|
||||
|
||||
matcher.toBeLoggedOnce();
|
||||
const entry = matcher.logs[0];
|
||||
|
||||
// Assert
|
||||
expect(entry).toEqual({
|
||||
level: 'error',
|
||||
message: 'override',
|
||||
context: 'OVR',
|
||||
});
|
||||
});
|
||||
|
||||
it('clear() очищает все записи', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX');
|
||||
logger.log('warn', 'B', 'CTX');
|
||||
|
||||
// Act
|
||||
logger.clear();
|
||||
const matcher = logger.any();
|
||||
|
||||
// Assert
|
||||
matcher.toBeNotLogged();
|
||||
});
|
||||
});
|
||||
|
||||
describe('TestingLogger — входные точки фильтрации', () => {
|
||||
it('any() возвращает матчёр со всеми текущими записями', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX1');
|
||||
logger.log('warn', 'B', 'CTX2');
|
||||
logger.log('error', 'C', 'CTX3');
|
||||
|
||||
// Act & Assert
|
||||
logger.any().toBeLoggedTimes(3);
|
||||
});
|
||||
|
||||
it('withMessage("X") создаёт стартовый матчёр с фильтром по message', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'X', 'CTX1');
|
||||
logger.log('warn', 'Y', 'CTX2');
|
||||
logger.log('error', 'X', 'CTX3');
|
||||
|
||||
// Act & Assert
|
||||
logger.withMessage('X').toBeLoggedTimes(2);
|
||||
logger.withMessage('Y').toBeLoggedTimes(1);
|
||||
logger.withMessage('Z').toBeLoggedTimes(0);
|
||||
});
|
||||
|
||||
it('withLevel(L) создаёт стартовый матчёр с фильтром по level', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX1');
|
||||
logger.log('error', 'B', 'CTX2');
|
||||
logger.log('error', 'C', 'CTX3');
|
||||
|
||||
// Act & Assert
|
||||
logger.withLevel('info').toBeLoggedTimes(1);
|
||||
logger.withLevel('error').toBeLoggedTimes(2);
|
||||
logger.withLevel('warn').toBeLoggedTimes(0);
|
||||
});
|
||||
|
||||
it('withContext("C") создаёт стартовый матчёр с фильтром по context', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'C');
|
||||
logger.log('warn', 'B', 'CTX2');
|
||||
logger.log('error', 'C', 'C');
|
||||
|
||||
// Act & Assert
|
||||
logger.withContext('C').toBeLoggedTimes(2);
|
||||
logger.withContext('CTX2').toBeLoggedTimes(1);
|
||||
logger.withContext('CTX3').toBeLoggedTimes(0);
|
||||
});
|
||||
|
||||
it('повторные вызовы стартовых фильтров независимы (каждый — новый матчёр)', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX');
|
||||
logger.log('info', 'B', 'CTX');
|
||||
|
||||
// Act
|
||||
const mA = logger.withMessage('A');
|
||||
const mB = logger.withMessage('B');
|
||||
|
||||
// Assert
|
||||
mA.toBeLoggedTimes(1);
|
||||
mB.toBeLoggedTimes(1);
|
||||
// Проверяем, что фильтры независимы
|
||||
expect(mA.logs[0].message).toBe('A');
|
||||
expect(mB.logs[0].message).toBe('B');
|
||||
});
|
||||
});
|
||||
|
||||
describe('TestingLoggerMatcher — фильтры (локальные)', () => {
|
||||
it('withMessage("X") фильтрует текущий набор по message', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'X', 'CTX1');
|
||||
logger.log('warn', 'Y', 'CTX2');
|
||||
logger.log('error', 'X', 'CTX3');
|
||||
logger.log('debug', 'Z', 'CTX4');
|
||||
|
||||
// Act
|
||||
const filtered = logger.any().withMessage('X');
|
||||
|
||||
// Assert
|
||||
filtered.toBeLoggedTimes(2); // Должно остаться только 2 записи с message === 'X'
|
||||
});
|
||||
|
||||
it('withLevel(L) фильтрует текущий набор по level', () => {
|
||||
// Arrange
|
||||
logger.log('warn', 'A', 'CTX1');
|
||||
logger.log('info', 'B', 'CTX2');
|
||||
logger.log('warn', 'C', 'CTX3');
|
||||
logger.log('error', 'D', 'CTX4');
|
||||
|
||||
// Act
|
||||
const filtered = logger.any().withLevel('warn');
|
||||
|
||||
// Assert
|
||||
filtered.toBeLoggedTimes(2); // Должно остаться только 2 записи с level === 'warn'
|
||||
});
|
||||
|
||||
it('withContext("C") фильтрует текущий набор по context', () => {
|
||||
// Arrange
|
||||
logger.log('warn', 'A', 'C');
|
||||
logger.log('info', 'B', 'CTX2');
|
||||
logger.log('warn', 'C', 'C');
|
||||
logger.log('error', 'D', 'CTX4');
|
||||
|
||||
// Act
|
||||
const filtered = logger.any().withContext('C');
|
||||
|
||||
// Assert
|
||||
filtered.toBeLoggedTimes(2); // Должно остаться только 2 записи с context === 'C'
|
||||
});
|
||||
|
||||
it('withDetails({k:v}) оставляет записи, где все пары совпали (логическое И)', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX', { a: 1, b: 'x' });
|
||||
logger.log('info', 'B', 'CTX', { a: 1 });
|
||||
logger.log('info', 'C', 'CTX', { b: 'x' });
|
||||
logger.log('info', 'D', 'CTX', { a: 1, b: 'x', c: true });
|
||||
|
||||
// Act
|
||||
const filtered = logger.any().withDetails({ a: 1, b: 'x' });
|
||||
|
||||
// Assert
|
||||
filtered.toBeLoggedTimes(2); // Должны остаться только записи, где одновременно a=1 и b='x'
|
||||
});
|
||||
|
||||
it('комбинация фильтров даёт пересечение условий', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'X', 'C', { a: 1 }); // подходит
|
||||
logger.log('info', 'X', 'C', { a: 2 }); // не подходит
|
||||
logger.log('info', 'Y', 'C', { a: 1 }); // не подходит
|
||||
logger.log('warn', 'X', 'C', { a: 1 }); // не подходит
|
||||
|
||||
// Act
|
||||
const filtered = logger
|
||||
.any()
|
||||
.withMessage('X')
|
||||
.withLevel('info')
|
||||
.withContext('C')
|
||||
.withDetails({ a: 1 });
|
||||
|
||||
// Assert
|
||||
filtered.toBeLoggedTimes(1); // Только одна запись удовлетворяет всем условиям
|
||||
});
|
||||
|
||||
it('порядок применения with* не влияет на результат (коммутативность)', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'X', 'C', { a: 1 }); // подходит
|
||||
logger.log('info', 'X', 'C', { a: 2 }); // не подходит
|
||||
logger.log('info', 'Y', 'C', { a: 1 }); // не подходит
|
||||
logger.log('warn', 'X', 'C', { a: 1 }); // не подходит
|
||||
|
||||
// Act
|
||||
const filtered1 = logger
|
||||
.any()
|
||||
.withMessage('X')
|
||||
.withLevel('info')
|
||||
.withContext('C')
|
||||
.withDetails({ a: 1 });
|
||||
const filtered2 = logger
|
||||
.any()
|
||||
.withDetails({ a: 1 })
|
||||
.withContext('C')
|
||||
.withLevel('info')
|
||||
.withMessage('X');
|
||||
|
||||
// Assert
|
||||
filtered1.toBeLoggedTimes(1);
|
||||
filtered2.toBeLoggedTimes(1);
|
||||
});
|
||||
|
||||
it('фильтры не мутируют исходный матчёр (иммутабельность)', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'X', 'CTX');
|
||||
logger.log('info', 'Y', 'CTX');
|
||||
|
||||
// Act
|
||||
const m0 = logger.any();
|
||||
const m1 = m0.withMessage('X');
|
||||
|
||||
// Assert
|
||||
m0.toBeLoggedTimes(2); // исходный набор
|
||||
m1.toBeLoggedTimes(1); // отфильтрованный
|
||||
m0.toBeLoggedTimes(2); // повторно исходный набор
|
||||
});
|
||||
|
||||
it('фильтр на пустом наборе остаётся пустым', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX');
|
||||
|
||||
// Act & Assert
|
||||
logger
|
||||
.any()
|
||||
.withMessage('non-existent')
|
||||
.withLevel('warn')
|
||||
.withContext('none')
|
||||
.toBeLoggedTimes(0);
|
||||
});
|
||||
|
||||
it('через withDetails можно проверять и другие поля', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX');
|
||||
|
||||
// Act & Assert
|
||||
logger
|
||||
.any()
|
||||
.withMessage('A')
|
||||
.withDetails({ level: 'info', context: 'CTX' })
|
||||
.toBeLoggedOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Паритет фильтров в обоих классах', () => {
|
||||
it('старт с TestingLogger.withX(...).withY(...).withZ(...) == any().withX(...).withY(...).withZ(...)', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'X', 'C', { a: 1 }); // подходит
|
||||
logger.log('info', 'X', 'C', { a: 2 }); // не подходит
|
||||
logger.log('info', 'Y', 'C', { a: 1 }); // не подходит
|
||||
logger.log('warn', 'X', 'C', { a: 1 }); // не подходит
|
||||
|
||||
// Act
|
||||
const fromStart = logger
|
||||
.withMessage('X')
|
||||
.withLevel('info')
|
||||
.withContext('C')
|
||||
.withDetails({ a: 1 });
|
||||
const fromAny = logger
|
||||
.any()
|
||||
.withMessage('X')
|
||||
.withLevel('info')
|
||||
.withContext('C')
|
||||
.withDetails({ a: 1 });
|
||||
|
||||
// Assert
|
||||
fromStart.toBeLoggedTimes(1);
|
||||
fromAny.toBeLoggedTimes(1);
|
||||
// Проверяем, что состав совпадает
|
||||
expect(JSON.stringify(fromStart.logs)).toBe(JSON.stringify(fromAny.logs));
|
||||
});
|
||||
});
|
||||
|
||||
describe('Матчеры наличия/отсутствия', () => {
|
||||
it('toBeLogged() проходит при >= 1 записи', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX');
|
||||
|
||||
// Act & Assert
|
||||
expect(() => logger.any().toBeLogged()).not.toThrow();
|
||||
});
|
||||
|
||||
it('toBeLogged() падает на пустом наборе', () => {
|
||||
// Arrange: ничего не добавляем
|
||||
|
||||
// Act & Assert
|
||||
expect(() => logger.any().toBeLogged()).toThrowError('No logs recorded');
|
||||
});
|
||||
|
||||
it('toBeNotLogged() проходит при 0 записях', () => {
|
||||
// Arrange: ничего не добавляем
|
||||
|
||||
// Act & Assert
|
||||
expect(() => logger.any().toBeNotLogged()).not.toThrow();
|
||||
});
|
||||
|
||||
it('toBeNotLogged() падает при >= 1 записи', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX');
|
||||
logger.log('warn', 'B', 'CTX');
|
||||
|
||||
// Act & Assert
|
||||
expect(() => logger.any().toBeNotLogged()).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Матчеры количества', () => {
|
||||
it('toBeLoggedOnce() проходит при ровно 1 записи', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX');
|
||||
|
||||
// Act & Assert
|
||||
expect(() => logger.any().toBeLoggedOnce()).not.toThrow();
|
||||
});
|
||||
|
||||
it('toBeLoggedOnce() падает при 0', () => {
|
||||
// Сценарий A: 0 записей
|
||||
expect(() => logger.any().toBeLoggedOnce()).toThrow();
|
||||
});
|
||||
|
||||
it('toBeLoggedOnce() падает при >1, сообщение содержит count и JSON', () => {
|
||||
// Сценарий B: >1 записей
|
||||
logger.log('info', 'A', 'CTX');
|
||||
logger.log('info', 'B', 'CTX');
|
||||
|
||||
expect(() => logger.any().toBeLoggedOnce()).toThrow();
|
||||
});
|
||||
|
||||
it('toBeLoggedTimes(n) проходит при точном совпадении количества', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX');
|
||||
logger.log('info', 'B', 'CTX');
|
||||
|
||||
// Act & Assert
|
||||
expect(() => logger.any().toBeLoggedTimes(2)).not.toThrow();
|
||||
});
|
||||
|
||||
it('toBeLoggedTimes(n) падает при несовпадении (сообщение: ожидаемое и фактическое)', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX');
|
||||
|
||||
// Act & Assert
|
||||
expect(() => logger.any().toBeLoggedTimes(2)).toThrow();
|
||||
});
|
||||
|
||||
it('toBeLoggedTimes(0) проходит на пустом наборе', () => {
|
||||
// Arrange: ничего не добавляем
|
||||
|
||||
// Act & Assert
|
||||
expect(() => logger.any().toBeLoggedTimes(0)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Детали и типы значений (withDetails / details)', () => {
|
||||
it('совпадение по string/number/boolean', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX', { a: 'x' });
|
||||
logger.log('info', 'B', 'CTX', { b: 1 });
|
||||
logger.log('info', 'C', 'CTX', { c: true });
|
||||
|
||||
// Act & Assert
|
||||
logger.any().withDetails({ a: 'x' }).toBeLoggedOnce();
|
||||
logger.any().withDetails({ b: 1 }).toBeLoggedOnce();
|
||||
logger.any().withDetails({ c: true }).toBeLoggedOnce();
|
||||
});
|
||||
|
||||
it('несуществующий ключ в фильтре исключает запись', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX', { a: 1 });
|
||||
|
||||
// Act & Assert
|
||||
logger.any().withDetails({ d: 42 }).toBeLoggedTimes(0);
|
||||
});
|
||||
|
||||
it('частичное несоответствие по одному из ключей исключает запись', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX', { a: 1, b: 2 });
|
||||
|
||||
// Act & Assert
|
||||
logger.any().withDetails({ a: 1, b: 999 }).toBeLoggedTimes(0);
|
||||
});
|
||||
|
||||
it('различие по типу (число vs строка) не считается совпадением', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX', { a: 1 });
|
||||
|
||||
// Act & Assert
|
||||
logger
|
||||
.any()
|
||||
.withDetails({ a: '1' as unknown as number })
|
||||
.toBeLoggedTimes(0);
|
||||
});
|
||||
|
||||
it('дополнительные поля в записи не мешают совпадению (подмножество)', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX', { a: 1, b: 2, c: 3 });
|
||||
|
||||
// Act & Assert
|
||||
logger.any().withDetails({ a: 1 }).toBeLoggedOnce();
|
||||
});
|
||||
|
||||
it('strictDetails требует точного совпадения ключей деталей (не допускает лишних полей)', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'X', 'CTX', { a: 1, b: 2 });
|
||||
|
||||
// Act & Assert
|
||||
// Обычный withDetails допускает совпадение по подмножеству
|
||||
logger.any().withDetails({ a: 1 }).toBeLoggedOnce();
|
||||
|
||||
// strictDetails требует точного совпадения — запись с лишним полем не должна подходить
|
||||
logger.any().withDetails({ a: 1 }).strictDetails().toBeLoggedTimes(0);
|
||||
});
|
||||
|
||||
it('strictDetails проходит при полном совпадении деталей', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'Y', 'CTX', { a: 1 });
|
||||
|
||||
// Act & Assert
|
||||
logger.any().withDetails({ a: 1 }).strictDetails().toBeLoggedOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Граничные случаи', () => {
|
||||
it('дубликаты идентичных логов учитываются поштучно в подсчёте', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX', { a: 1 });
|
||||
logger.log('info', 'A', 'CTX', { a: 1 });
|
||||
logger.log('info', 'A', 'CTX', { a: 1 });
|
||||
|
||||
// Act & Assert
|
||||
logger.any().withDetails({ a: 1 }).toBeLoggedTimes(3);
|
||||
});
|
||||
|
||||
it('одинаковые level/message/context, но разные details различаются withDetails', () => {
|
||||
// Arrange
|
||||
logger.log('info', 'A', 'CTX', { a: 1 });
|
||||
logger.log('info', 'A', 'CTX', { a: 2 });
|
||||
|
||||
// Act & Assert
|
||||
logger.any().withDetails({ a: 1 }).toBeLoggedOnce();
|
||||
logger.any().withDetails({ a: 2 }).toBeLoggedOnce();
|
||||
});
|
||||
|
||||
it('пустые строки корректно фильтруются: withMessage("") / withContext("")', () => {
|
||||
// Arrange
|
||||
logger.log('info', '', 'CTX', { a: 1 });
|
||||
logger.log('info', 'A', '', { a: 2 });
|
||||
logger.log('info', '', '', { a: 3 });
|
||||
|
||||
// Act & Assert
|
||||
logger.withMessage('').toBeLoggedTimes(2); // две записи с пустым message
|
||||
logger.withContext('').toBeLoggedTimes(2); // две записи с пустым context
|
||||
});
|
||||
|
||||
it('smoke: большое количество записей не ломает фильтры', () => {
|
||||
// Arrange
|
||||
const N = 1000;
|
||||
|
||||
for (let i = 0; i < N; i++) {
|
||||
logger.log('info', `msg${i % 10}`, `CTX${i % 5}`, { a: i % 3, b: i });
|
||||
}
|
||||
|
||||
// Act & Assert
|
||||
logger.withMessage('msg1').toBeLoggedTimes(100);
|
||||
logger.withContext('CTX2').toBeLoggedTimes(200);
|
||||
logger
|
||||
.any()
|
||||
.withDetails({ a: 0 })
|
||||
.toBeLoggedTimes(Math.floor(N / 3) + (N % 3 > 0 ? 1 : 0));
|
||||
logger.any().withDetails({ b: 42 }).toBeLoggedOnce();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import * as colorette from 'colorette';
|
||||
|
||||
import { LogLevel } from '../logger.class';
|
||||
|
||||
export interface LogEntry {
|
||||
level: LogLevel;
|
||||
message: string;
|
||||
context: string;
|
||||
[extra: string]: unknown;
|
||||
}
|
||||
|
||||
export function fail(message: string): void {
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
type ErrorConstructorWithCapture = ErrorConstructor & {
|
||||
captureStackTrace?: (targetObject: object, constructorOpt?: unknown) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Декоратор для методов матчеров:
|
||||
* Если метод бросил ошибку — стек "подрезается" так,
|
||||
* чтобы указать на строку вызова матчера в тесте (а не внутрь реализации).
|
||||
*/
|
||||
export function PrettifyStackTrace(): MethodDecorator {
|
||||
return (_target, _key, descriptor: PropertyDescriptor) => {
|
||||
const original = descriptor.value as (...args: unknown[]) => unknown;
|
||||
|
||||
function wrap(this: unknown, ...args: unknown[]) {
|
||||
try {
|
||||
return original.apply(this, args);
|
||||
} catch (err) {
|
||||
(Error as ErrorConstructorWithCapture).captureStackTrace?.(err as object, wrap);
|
||||
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
descriptor.value = wrap;
|
||||
|
||||
return descriptor;
|
||||
};
|
||||
}
|
||||
|
||||
export function showLogObject({ level, context, message, ...details }: LogEntry) {
|
||||
const l = colorette.blue(level);
|
||||
const c = colorette.bold(colorette.magenta(context));
|
||||
const m = colorette.underline(colorette.white(message));
|
||||
|
||||
process.stdout.write(` ${l} ${c} ${m}\n`);
|
||||
|
||||
showLogDetails(details);
|
||||
}
|
||||
|
||||
export function showLogDetails(details: Record<string, unknown>) {
|
||||
Object.keys(details).forEach((key) => {
|
||||
if (details[key] === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
process.stdout.write(
|
||||
` ${colorette.blue(key)}: ${colorette.yellow(String(details[key]))}\n`,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
|
||||
import { AppModule } from './app/app.module';
|
||||
import { getBaseLogger, LocalLoggerModule, Logger } from './logger';
|
||||
|
||||
async function start() {
|
||||
const PORT = process.env.PORT || 5000;
|
||||
|
||||
const app = await NestFactory.create(AppModule, {
|
||||
bufferLogs: true,
|
||||
});
|
||||
|
||||
// Подменяем логгер Nest на pino; накопленный в буфере вывод сбрасывается в него же
|
||||
LocalLoggerModule.setup(app);
|
||||
|
||||
const logger = new Logger('Bootstrap');
|
||||
|
||||
logger.log('Logging started', {
|
||||
level: getBaseLogger().level,
|
||||
pretty: process.env.NODE_ENV !== 'production' && process.env.LOG_PRETTY !== 'false',
|
||||
});
|
||||
|
||||
// настройка 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);
|
||||
|
||||
logger.log('Server started', { port: PORT });
|
||||
}
|
||||
start();
|
||||
@@ -0,0 +1,3 @@
|
||||
// Файл сгенерирован автоматически (tools/buildDataSource.ts). Не редактировать вручную.
|
||||
|
||||
export const migrations = [];
|
||||
@@ -0,0 +1 @@
|
||||
import 'reflect-metadata';
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.app.json"
|
||||
},
|
||||
{
|
||||
"path": "./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"
|
||||
]
|
||||
}
|
||||
@@ -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: {
|
||||
'@it-smi/api': resolve(import.meta.dirname, 'src'),
|
||||
},
|
||||
},
|
||||
test: {
|
||||
name: '@it-smi/api',
|
||||
globals: true,
|
||||
environment: 'node',
|
||||
include: ['src/**/*.{test,spec}.ts'],
|
||||
setupFiles: ['src/test-setup.ts'],
|
||||
coverage: {
|
||||
reportsDirectory: './test-output/vitest/coverage',
|
||||
provider: 'v8',
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -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: {
|
||||
'@it-smi/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(['@it-smi/']),
|
||||
...plugins,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createApiWebpackConfig };
|
||||
@@ -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'),
|
||||
}),
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
const { createApiWebpackConfig } = require('./webpack.base');
|
||||
|
||||
/**
|
||||
* Отдельный бандл DataSource для typeorm CLI внутри контейнера.
|
||||
*
|
||||
* Собирается в тот же dist, что и main.js, поэтому clean: false —
|
||||
* иначе сборка затрёт основной бандл.
|
||||
*
|
||||
* Запускать после основного webpack.config.js (см. таргет api:build,
|
||||
* там же parallel: false).
|
||||
*/
|
||||
module.exports = createApiWebpackConfig({
|
||||
output: {
|
||||
filename: 'data-source.js',
|
||||
// Не чистим dist: рядом лежит main.js от основной сборки.
|
||||
clean: false,
|
||||
library: {
|
||||
type: 'commonjs2',
|
||||
export: 'default',
|
||||
},
|
||||
},
|
||||
nxPlugin: {
|
||||
main: './src/config/typeorm.config.ts',
|
||||
generatePackageJson: false,
|
||||
// Бандл запускается только руками через docker exec — .map в образе не нужен.
|
||||
sourceMap: false,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
:80 {
|
||||
respond /health "OK" {
|
||||
close
|
||||
}
|
||||
}
|
||||
|
||||
jt4d.ru, http://*.jt4d.jt4d.ru.net {
|
||||
root * /app
|
||||
encode gzip
|
||||
|
||||
# Обработка API
|
||||
handle /api/* {
|
||||
reverse_proxy api:5000
|
||||
}
|
||||
|
||||
# Обработка остального (SPA)
|
||||
handle {
|
||||
try_files {path} /index.html
|
||||
file_server
|
||||
|
||||
@static path *.js *.css *.woff *.woff2 *.svg *.png *.jpg *.jpeg *.gif *.ico
|
||||
header @static Cache-Control "public, max-age=31536000, immutable"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
:80 {
|
||||
root * /app
|
||||
encode gzip
|
||||
|
||||
handle /api/* {
|
||||
reverse_proxy api:5000
|
||||
}
|
||||
|
||||
handle {
|
||||
try_files {path} /index.html
|
||||
file_server
|
||||
|
||||
@static path *.js *.css *.woff *.woff2 *.svg *.png *.jpg *.jpeg *.gif *.ico
|
||||
header @static Cache-Control "public, max-age=31536000, immutable"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
FROM git.jt4d.ru/jt4d/caddy:2-alpine
|
||||
|
||||
ARG CADDYFILE=Caddyfile
|
||||
|
||||
COPY ./dist /app
|
||||
|
||||
EXPOSE 80 443
|
||||
|
||||
COPY ${CADDYFILE} /etc/caddy/Caddyfile
|
||||
|
||||
HEALTHCHECK --interval=10s --timeout=3s --retries=3 \
|
||||
CMD curl -f http://localhost:80/health || exit 1
|
||||
@@ -0,0 +1,4 @@
|
||||
import nx from '@nx/eslint-plugin';
|
||||
import baseConfig from '../../eslint.config.mjs';
|
||||
|
||||
export default [...nx.configs['flat/react'], ...baseConfig];
|
||||
@@ -0,0 +1,29 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Web</title>
|
||||
<base href="/" />
|
||||
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1"
|
||||
/>
|
||||
<link
|
||||
rel="icon"
|
||||
type="image/x-icon"
|
||||
href="/favicon.ico"
|
||||
/>
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="/src/styles.css"
|
||||
/>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script
|
||||
type="module"
|
||||
src="/src/main.tsx"
|
||||
></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "@it-smi/web",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-router-dom": "^6.30.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/dom": "^10.4.0",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^4.2.0",
|
||||
"eslint-plugin-jsx-a11y": "^6.10.1",
|
||||
"eslint-plugin-react": "^7.35.0",
|
||||
"eslint-plugin-react-hooks": "^5.0.0",
|
||||
"jsdom": "^30.0.1",
|
||||
"tailwindcss": "^3.4.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { dirname, join } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: { config: join(__dirname, 'tailwind.config.js') },
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,88 @@
|
||||
{
|
||||
"name": "web",
|
||||
"$schema": "../../node_modules/nx/schemas/project-schema.json",
|
||||
"sourceRoot": "apps/web/src",
|
||||
"projectType": "application",
|
||||
"tags": [],
|
||||
"targets": {
|
||||
"clean": {
|
||||
"executor": "nx:run-commands",
|
||||
"options": {
|
||||
"commands": [
|
||||
"rimraf apps/web/dist"
|
||||
]
|
||||
}
|
||||
},
|
||||
"build": {
|
||||
"executor": "@nx/vite:build",
|
||||
"options": {
|
||||
"outputPath": "apps/web/dist/",
|
||||
"base": "/",
|
||||
"viteConfig": "apps/web/vite.config.ts"
|
||||
}
|
||||
},
|
||||
"typecheck": {
|
||||
"executor": "nx:run-commands",
|
||||
"options": {
|
||||
"command": "tsc --noEmit -p tsconfig.spec.json",
|
||||
"cwd": "apps/web"
|
||||
}
|
||||
},
|
||||
"lint": {
|
||||
"executor": "@nx/eslint:lint",
|
||||
"options": {
|
||||
"lintFilePatterns": [
|
||||
"{projectRoot}/**/*.{ts,tsx}"
|
||||
],
|
||||
"eslintConfig": "{projectRoot}/eslint.config.mjs",
|
||||
"fix": true
|
||||
}
|
||||
},
|
||||
"lint-check": {
|
||||
"executor": "@nx/eslint:lint",
|
||||
"options": {
|
||||
"lintFilePatterns": [
|
||||
"{projectRoot}/**/*.{ts,tsx}"
|
||||
],
|
||||
"eslintConfig": "{projectRoot}/eslint.config.mjs"
|
||||
}
|
||||
},
|
||||
"format": {
|
||||
"executor": "nx:run-commands",
|
||||
"options": {
|
||||
"parallel": false,
|
||||
"commands": [
|
||||
"prettier --write {projectRoot}",
|
||||
"stylelint --fix \"{projectRoot}/**/*.{scss,css}\""
|
||||
]
|
||||
}
|
||||
},
|
||||
"format-check": {
|
||||
"executor": "nx:run-commands",
|
||||
"options": {
|
||||
"parallel": false,
|
||||
"commands": [
|
||||
"prettier --check {projectRoot}",
|
||||
"stylelint \"{projectRoot}/**/*.{scss,css}\""
|
||||
]
|
||||
}
|
||||
},
|
||||
"serve": {
|
||||
"executor": "@nx/vite:dev-server",
|
||||
"defaultConfiguration": "development",
|
||||
"options": {
|
||||
"buildTarget": "web:build",
|
||||
"port": 5173
|
||||
},
|
||||
"configurations": {}
|
||||
},
|
||||
"preview": {
|
||||
"executor": "@nx/vite:preview-server",
|
||||
"options": {
|
||||
"buildTarget": "web:build",
|
||||
"port": 5173
|
||||
},
|
||||
"configurations": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,24 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
|
||||
import App from './app';
|
||||
|
||||
describe('App', () => {
|
||||
it('should render successfully', () => {
|
||||
const { baseElement } = render(
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>,
|
||||
);
|
||||
expect(baseElement).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should have a greeting as the title', () => {
|
||||
const { getAllByText } = render(
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>,
|
||||
);
|
||||
expect(getAllByText(/Hello @it-smi\/web/i).length > 0).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Link, Route, Routes } from 'react-router-dom';
|
||||
|
||||
import { HealthPage } from '../pages/HealthPage';
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Hello @it-smi/web</h1>
|
||||
|
||||
<nav role="navigation">
|
||||
<ul>
|
||||
<li>
|
||||
<Link to="/">Home</Link>
|
||||
</li>
|
||||
<li>
|
||||
<Link to="/page-2">Page 2</Link>
|
||||
</li>
|
||||
<li>
|
||||
<Link to="/health">Health</Link>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<Routes>
|
||||
<Route
|
||||
path="/"
|
||||
element={<div>This is the generated root route.</div>}
|
||||
/>
|
||||
<Route
|
||||
path="/health"
|
||||
element={<HealthPage />}
|
||||
/>
|
||||
<Route
|
||||
path="/page-2"
|
||||
element={<div>Page 2</div>}
|
||||
/>
|
||||
</Routes>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
Whitespace-only changes.
@@ -0,0 +1,16 @@
|
||||
import { StrictMode } from 'react';
|
||||
|
||||
import * as ReactDOM from 'react-dom/client';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
|
||||
import App from './app/app';
|
||||
|
||||
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
|
||||
|
||||
root.render(
|
||||
<StrictMode>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,30 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
|
||||
import { HealthPage } from './HealthPage';
|
||||
|
||||
describe('HealthPage', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('показывает версию API из ответа сервера', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ status: 'ok', version: 'v1.2.3' }),
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
render(<HealthPage />);
|
||||
|
||||
expect(await screen.findByText('v1.2.3')).toBeTruthy();
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/health');
|
||||
});
|
||||
|
||||
it('показывает, что API недоступен, если запрос упал', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network')));
|
||||
|
||||
render(<HealthPage />);
|
||||
|
||||
expect(await screen.findByText('down')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export function HealthPage() {
|
||||
const webVersion = import.meta.env.APP_VERSION || 'unknown';
|
||||
const [apiVersion, setApiVersion] = useState<string | null>(null);
|
||||
const [apiError, setApiError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/api/health')
|
||||
.then((r) => {
|
||||
if (!r.ok) throw new Error(String(r.status));
|
||||
return r.json();
|
||||
})
|
||||
.then((d) => setApiVersion(d?.version ?? 'unknown'))
|
||||
.catch(() => setApiError(true));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="min-h-screen"
|
||||
style={{ backgroundColor: 'var(--bg-primary)' }}
|
||||
>
|
||||
<div className="max-w-lg mx-auto px-4 py-16">
|
||||
<h1
|
||||
className="text-2xl font-bold mb-8"
|
||||
style={{ color: 'var(--text-primary)' }}
|
||||
>
|
||||
Health
|
||||
</h1>
|
||||
<div
|
||||
className="rounded-lg border p-6 space-y-4"
|
||||
style={{
|
||||
backgroundColor: 'var(--bg-secondary)',
|
||||
borderColor: 'var(--border-color)',
|
||||
}}
|
||||
>
|
||||
<div className="flex justify-between items-center">
|
||||
<span
|
||||
className="text-sm font-medium"
|
||||
style={{ color: 'var(--text-secondary)' }}
|
||||
>
|
||||
Web version
|
||||
</span>
|
||||
<span
|
||||
className="text-sm font-mono"
|
||||
style={{ color: 'var(--text-primary)' }}
|
||||
>
|
||||
{webVersion}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span
|
||||
className="text-sm font-medium"
|
||||
style={{ color: 'var(--text-secondary)' }}
|
||||
>
|
||||
API version
|
||||
</span>
|
||||
{apiError ? (
|
||||
<span
|
||||
className="text-sm font-mono"
|
||||
style={{ color: 'var(--color-error, #ef4444)' }}
|
||||
>
|
||||
down
|
||||
</span>
|
||||
) : (
|
||||
<span
|
||||
className="text-sm font-mono"
|
||||
style={{ color: 'var(--text-primary)' }}
|
||||
>
|
||||
{apiVersion ?? '...'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
/* You can add global styles to this file, and also import other style files */
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,19 @@
|
||||
import { dirname, join } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
import { createGlobPatternsForDependencies } from '@nx/react/tailwind';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
export default {
|
||||
content: [
|
||||
join(__dirname, './src/**/*!(*.stories|*.spec).{ts,tsx,html}'),
|
||||
join(__dirname, './index.html'),
|
||||
...createGlobPatternsForDependencies(__dirname),
|
||||
],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": [
|
||||
"ES2020",
|
||||
"DOM",
|
||||
"DOM.Iterable"
|
||||
],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"files": [],
|
||||
"include": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.app.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.spec.json"
|
||||
}
|
||||
],
|
||||
"extends": "../../tsconfig.base.json"
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"extends": "./tsconfig.app.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./out-tsc/vitest",
|
||||
"types": [
|
||||
"vitest/globals",
|
||||
"vitest/importMeta",
|
||||
"vite/client",
|
||||
"node",
|
||||
"vitest",
|
||||
"@nx/react/typings/cssmodule.d.ts",
|
||||
"@nx/react/typings/image.d.ts"
|
||||
]
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/// <reference types='vitest' />
|
||||
import react from '@vitejs/plugin-react';
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig(() => ({
|
||||
root: import.meta.dirname,
|
||||
cacheDir: '../../node_modules/.vite/apps/web',
|
||||
server: {
|
||||
port: 5173,
|
||||
host: 'localhost',
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:5000',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
preview: {
|
||||
port: 5173,
|
||||
host: 'localhost',
|
||||
},
|
||||
plugins: [react()],
|
||||
envPrefix: ['VITE_', 'APP_'],
|
||||
// Uncomment this if you are using workers.
|
||||
// worker: {
|
||||
// plugins: [],
|
||||
// },
|
||||
build: {
|
||||
outDir: './dist',
|
||||
emptyOutDir: true,
|
||||
reportCompressedSize: true,
|
||||
commonjsOptions: {
|
||||
transformMixedEsModules: true,
|
||||
},
|
||||
},
|
||||
test: {
|
||||
name: '@it-smi/web',
|
||||
watch: false,
|
||||
globals: true,
|
||||
environment: 'jsdom',
|
||||
include: ['{src,tests}/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
|
||||
reporters: ['default'],
|
||||
coverage: {
|
||||
reportsDirectory: './test-output/vitest/coverage',
|
||||
provider: 'v8' as const,
|
||||
},
|
||||
},
|
||||
}));
|
||||
@@ -0,0 +1,31 @@
|
||||
services:
|
||||
web:
|
||||
container_name: it-smi_${BRANCH}_web
|
||||
image: git.jt4d.ru/public/it-smi/web:${BRANCH}
|
||||
labels:
|
||||
caddy: ${BRANCH}.it-smi.jt4d.ru.net
|
||||
caddy.reverse_proxy: '{{upstreams 80}}'
|
||||
restart: always
|
||||
init: true
|
||||
networks:
|
||||
- 'net'
|
||||
|
||||
api:
|
||||
container_name: it-smi_${BRANCH}_api
|
||||
image: git.jt4d.ru/public/it-smi/api:${BRANCH}
|
||||
environment:
|
||||
# POSTGRES_* пишет staging-db-postgres в .env каталога деплоя.
|
||||
# Синтаксис ${X:-} намеренно необязательный: ${X:?} валит и pull, и down.
|
||||
POSTGRES_USER: ${POSTGRES_USER:-}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-}
|
||||
POSTGRES_HOST: ${POSTGRES_HOST:-}
|
||||
POSTGRES_PORT: ${POSTGRES_PORT:-5432}
|
||||
restart: always
|
||||
init: true
|
||||
networks:
|
||||
- 'net'
|
||||
|
||||
networks:
|
||||
net:
|
||||
external: true
|
||||
@@ -0,0 +1,116 @@
|
||||
import nx from '@nx/eslint-plugin';
|
||||
import importPlugin from 'eslint-plugin-import-x';
|
||||
import unusedImports from 'eslint-plugin-unused-imports';
|
||||
import { defineConfig, globalIgnores } from 'eslint/config';
|
||||
|
||||
export default defineConfig([
|
||||
...nx.configs['flat/base'],
|
||||
...nx.configs['flat/typescript'],
|
||||
...nx.configs['flat/javascript'],
|
||||
globalIgnores([
|
||||
'**/dist',
|
||||
'**/out-tsc',
|
||||
'**/vite.config.*.timestamp*',
|
||||
'**/vitest.config.*.timestamp*',
|
||||
]),
|
||||
{
|
||||
files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],
|
||||
plugins: {
|
||||
'import-x': importPlugin,
|
||||
'unused-imports': unusedImports,
|
||||
},
|
||||
rules: {
|
||||
'@nx/enforce-module-boundaries': [
|
||||
'error',
|
||||
{
|
||||
enforceBuildableLibDependency: true,
|
||||
allow: ['^.*/eslint(\\.base)?\\.config\\.[cm]?[jt]s$'],
|
||||
allowCircularSelfDependency: true,
|
||||
depConstraints: [
|
||||
{
|
||||
sourceTag: '*',
|
||||
onlyDependOnLibsWithTags: ['*'],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
'@typescript-eslint/no-empty-function': 'warn',
|
||||
'@typescript-eslint/no-inferrable-types': 'warn',
|
||||
'no-restricted-globals': 'warn',
|
||||
|
||||
'import-x/order': [
|
||||
'error',
|
||||
{
|
||||
pathGroups: [
|
||||
{
|
||||
pattern: 'react',
|
||||
group: 'builtin',
|
||||
position: 'before',
|
||||
},
|
||||
{
|
||||
pattern: '@it-smi/**',
|
||||
group: 'internal',
|
||||
},
|
||||
],
|
||||
|
||||
pathGroupsExcludedImportTypes: ['react'],
|
||||
'newlines-between': 'always',
|
||||
groups: ['builtin', 'external', 'internal', 'parent', ['sibling', 'index']],
|
||||
|
||||
alphabetize: {
|
||||
order: 'asc',
|
||||
caseInsensitive: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
'sort-imports': [
|
||||
'error',
|
||||
{
|
||||
ignoreCase: true,
|
||||
ignoreDeclarationSort: true,
|
||||
ignoreMemberSort: false,
|
||||
memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single'],
|
||||
allowSeparatedGroups: false,
|
||||
},
|
||||
],
|
||||
'unused-imports/no-unused-imports': 'error',
|
||||
'no-unused-vars': 'off',
|
||||
'@typescript-eslint/no-unused-vars': 'off',
|
||||
'unused-imports/no-unused-vars': [
|
||||
'error',
|
||||
{
|
||||
vars: 'all',
|
||||
varsIgnorePattern: '^_',
|
||||
args: 'after-used',
|
||||
argsIgnorePattern: '^_',
|
||||
caughtErrors: 'all',
|
||||
caughtErrorsIgnorePattern: '^_',
|
||||
},
|
||||
],
|
||||
'import-x/no-duplicates': 'error',
|
||||
'@typescript-eslint/ban-ts-comment': [
|
||||
'error',
|
||||
{
|
||||
'ts-ignore': 'allow-with-description',
|
||||
'ts-nocheck': 'allow-with-description',
|
||||
'ts-check': false,
|
||||
'ts-expect-error': false,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: [
|
||||
'**/*.ts',
|
||||
'**/*.tsx',
|
||||
'**/*.cts',
|
||||
'**/*.mts',
|
||||
'**/*.js',
|
||||
'**/*.jsx',
|
||||
'**/*.cjs',
|
||||
'**/*.mjs',
|
||||
],
|
||||
// Override or add rules here
|
||||
rules: {},
|
||||
},
|
||||
]);
|
||||
@@ -0,0 +1,110 @@
|
||||
{
|
||||
"$schema": "./node_modules/nx/schemas/nx-schema.json",
|
||||
"defaultBase": "master",
|
||||
"namedInputs": {
|
||||
"default": [
|
||||
"{projectRoot}/**/*",
|
||||
"sharedGlobals"
|
||||
],
|
||||
"production": [
|
||||
"default",
|
||||
"!{projectRoot}/.eslintrc.json",
|
||||
"!{projectRoot}/eslint.config.mjs",
|
||||
"!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)",
|
||||
"!{projectRoot}/tsconfig.spec.json",
|
||||
"!{projectRoot}/src/test-setup.[jt]s"
|
||||
],
|
||||
"sharedGlobals": []
|
||||
},
|
||||
"plugins": [
|
||||
{
|
||||
"plugin": "@nx/js/typescript",
|
||||
"options": {
|
||||
"typecheck": {
|
||||
"targetName": "typecheck"
|
||||
},
|
||||
"build": {
|
||||
"targetName": "build",
|
||||
"configName": "tsconfig.lib.json",
|
||||
"buildDepsName": "build-deps",
|
||||
"watchDepsName": "watch-deps"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"plugin": "@nx/eslint/plugin",
|
||||
"options": {
|
||||
"targetName": "lint"
|
||||
}
|
||||
},
|
||||
{
|
||||
"plugin": "@nx/vite/plugin",
|
||||
"options": {
|
||||
"buildTargetName": "build",
|
||||
"testTargetName": "test",
|
||||
"serveTargetName": "serve",
|
||||
"devTargetName": "dev",
|
||||
"previewTargetName": "preview",
|
||||
"serveStaticTargetName": "serve-static",
|
||||
"typecheckTargetName": "typecheck",
|
||||
"buildDepsTargetName": "build-deps",
|
||||
"watchDepsTargetName": "watch-deps"
|
||||
}
|
||||
},
|
||||
{
|
||||
"plugin": "@nx/vitest",
|
||||
"options": {
|
||||
"testTargetName": "test",
|
||||
"ciTargetName": "test-ci",
|
||||
"testMode": "watch"
|
||||
}
|
||||
},
|
||||
{
|
||||
"plugin": "@nx/webpack/plugin",
|
||||
"options": {
|
||||
"buildTargetName": "build",
|
||||
"serveTargetName": "serve",
|
||||
"previewTargetName": "preview",
|
||||
"buildDepsTargetName": "build-deps",
|
||||
"watchDepsTargetName": "watch-deps",
|
||||
"serveStaticTargetName": "serve-static"
|
||||
}
|
||||
}
|
||||
],
|
||||
"targetDefaults": {
|
||||
"test": {
|
||||
"dependsOn": [
|
||||
"^build"
|
||||
]
|
||||
},
|
||||
"db-{show,migrate,revert,drop}": {
|
||||
"options": {
|
||||
"env": {
|
||||
"TS_NODE_PROJECT": "apps/api/tsconfig.app.json",
|
||||
"NODE_OPTIONS": "-r tsconfig-paths/register"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"generators": {
|
||||
"@nx/react": {
|
||||
"application": {
|
||||
"babel": true,
|
||||
"style": "tailwind",
|
||||
"linter": "eslint",
|
||||
"bundler": "vite"
|
||||
},
|
||||
"component": {
|
||||
"style": "tailwind"
|
||||
},
|
||||
"library": {
|
||||
"style": "tailwind",
|
||||
"linter": "eslint"
|
||||
}
|
||||
}
|
||||
},
|
||||
"tui": {
|
||||
"enabled": false
|
||||
},
|
||||
"analytics": false
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
{
|
||||
"name": "@org/source",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"workspaces": [
|
||||
"apps/*",
|
||||
"packages/*"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "nx run-many -t build",
|
||||
"clean": "nx run-many -t clean",
|
||||
"db-drop": "nx run api:db-drop",
|
||||
"db-migrate": "nx run api:db-migrate",
|
||||
"db-migrations-list": "nx run api:db-migrations-list",
|
||||
"db-restore": "nx run api:db-restore",
|
||||
"db-revert": "nx run api:db-revert",
|
||||
"db-show": "nx run api:db-show",
|
||||
"db-snapshot": "nx run api:db-snapshot",
|
||||
"lint": "run-s lint:fix",
|
||||
"lint:fix": "run-s lint:*:fix lint:typecheck",
|
||||
"lint:branch-name": "validate-branch-name",
|
||||
"lint:check": "run-s lint:typecheck lint:*:check",
|
||||
"lint:eslint:check": "nx run-many -t lint-check",
|
||||
"lint:eslint:fix": "nx run-many -t lint",
|
||||
"lint:format:check": "nx run-many -t format-check",
|
||||
"lint:format:fix": "nx run-many -t format",
|
||||
"lint:typecheck": "nx run-many -t typecheck",
|
||||
"prepare": "husky",
|
||||
"rebuild": "nx run-many -t clean && nx run-many -t build",
|
||||
"start": "nx run-many -t serve --parallel"
|
||||
},
|
||||
"lint-staged": {
|
||||
"*.{json,ts,tsx,js,jsx,js,mjs,md,mdx,yaml,yml}": "prettier --write",
|
||||
"{src,e2e}/**/*.{ts,tsx}": "eslint --quiet --fix",
|
||||
"*.{scss,css}": "stylelint --fix",
|
||||
"package.json": "sort-package-json"
|
||||
},
|
||||
"resolutions": {
|
||||
"vite": "^7.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"reflect-metadata": "^0.1.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.8.0",
|
||||
"@nx/eslint": "^22.5.1",
|
||||
"@nx/eslint-plugin": "^22.5.1",
|
||||
"@nx/js": "^22.5.1",
|
||||
"@nx/nest": "^22.5.1",
|
||||
"@nx/node": "^22.5.1",
|
||||
"@nx/react": "^22.5.1",
|
||||
"@nx/vite": "^22.5.1",
|
||||
"@nx/vitest": "^22.5.1",
|
||||
"@nx/web": "^22.5.1",
|
||||
"@nx/webpack": "^22.5.1",
|
||||
"@swc-node/register": "^1.11.1",
|
||||
"@swc/cli": "~0.8.0",
|
||||
"@swc/core": "^1.15.8",
|
||||
"@swc/helpers": "^0.5.18",
|
||||
"@types/lodash": "^4.17.24",
|
||||
"@types/multer": "^2.3.0",
|
||||
"@types/node": "^20.19.9",
|
||||
"@types/pg": "^8.20.0",
|
||||
"@vitest/coverage-v8": "^4.0.0",
|
||||
"@vitest/ui": "^4.0.0",
|
||||
"autoprefixer": "^10.4.13",
|
||||
"eslint": "^9.8.0",
|
||||
"eslint-config-prettier": "^10.0.0",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
"eslint-plugin-import-x": "^4.16.2",
|
||||
"eslint-plugin-unused-imports": "^4.4.1",
|
||||
"husky": "^9.1.7",
|
||||
"lint-staged": "^16.2.7",
|
||||
"lodash": "^4.17.21",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"nx": "^22.5.1",
|
||||
"prettier": "^3.3.3",
|
||||
"rimraf": "^6.1.3",
|
||||
"sort-package-json": "^3.6.1",
|
||||
"stylelint": "^17.14.1",
|
||||
"stylelint-config-prettier-scss": "^1.0.0",
|
||||
"stylelint-config-recess-order": "^7.8.0",
|
||||
"stylelint-config-standard": "^40.0.0",
|
||||
"stylelint-config-standard-scss": "^17.0.0",
|
||||
"stylelint-order": "^8.1.1",
|
||||
"stylelint-prettier": "^5.0.3",
|
||||
"stylelint-scss": "^7.2.0",
|
||||
"ts-loader": "^9.4.3",
|
||||
"ts-node": "^10.9.1",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"tslib": "^2.3.0",
|
||||
"typescript": "~5.9.2",
|
||||
"typescript-eslint": "^8.40.0",
|
||||
"unplugin-swc": "^1.5.10",
|
||||
"validate-branch-name": "=1.3.1",
|
||||
"vite": "^7.0.0",
|
||||
"vitest": "^4.0.0"
|
||||
},
|
||||
"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e",
|
||||
"nx": {
|
||||
"includedScripts": []
|
||||
},
|
||||
"validate-branch-name": {
|
||||
"pattern": "(^(i\\d+-)?[a-z0-9-]{2,40}$|^\\(.*)",
|
||||
"errorMsg": "branch name must be like 'i777-short-description'"
|
||||
}
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "it-smi",
|
||||
"$schema": "./node_modules/nx/schemas/project-schema.json",
|
||||
"targets": {
|
||||
"lint": {
|
||||
"executor": "@nx/eslint:lint",
|
||||
"options": {
|
||||
"lintFilePatterns": [
|
||||
"tools/**/*.{ts,js}",
|
||||
"*.{ts,mjs}"
|
||||
],
|
||||
"fix": true
|
||||
}
|
||||
},
|
||||
"lint-check": {
|
||||
"executor": "@nx/eslint:lint",
|
||||
"options": {
|
||||
"lintFilePatterns": [
|
||||
"tools/**/*.{ts,js}",
|
||||
"*.{ts,mjs}"
|
||||
]
|
||||
}
|
||||
},
|
||||
"format": {
|
||||
"executor": "nx:run-commands",
|
||||
"options": {
|
||||
"command": "prettier --write . \"!apps/**\" \"!packages/**\""
|
||||
}
|
||||
},
|
||||
"format-check": {
|
||||
"executor": "nx:run-commands",
|
||||
"options": {
|
||||
"command": "prettier --check . \"!apps/**\" \"!packages/**\""
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import { type Dirent, existsSync, readdirSync, readFileSync, writeFileSync } from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
import { format, resolveConfig } from 'prettier';
|
||||
|
||||
export const workspaceRoot = path.resolve(__dirname, '..');
|
||||
const apiSrcDir = path.join(workspaceRoot, 'apps', 'api', 'src');
|
||||
const outputFile = path.join(apiSrcDir, 'migrations.ts');
|
||||
// Миграции лежат по модулям: apps/api/src/<module>/migrations/<timestamp>-<name>.ts.
|
||||
const MIGRATIONS_DIR_NAME = 'migrations';
|
||||
|
||||
const HEADER =
|
||||
'// Файл сгенерирован автоматически (tools/buildDataSource.ts). Не редактировать вручную.';
|
||||
|
||||
// Только именованный экспорт: render() строит именованный импорт, поэтому
|
||||
// `export default class` всё равно дал бы не компилирующийся файл — пусть лучше
|
||||
// падает на понятном "не найден export class".
|
||||
const EXPORT_CLASS_RE = /export\s+class\s+(\w+)/g;
|
||||
// Ровно 13 цифр: TypeORM берёт timestamp как parseInt(className.substr(-13))
|
||||
// (MigrationExecutor.getMigrations) и падает, если там не число.
|
||||
const TIMESTAMP_PREFIX_RE = /^(\d{13})-/;
|
||||
// Файлы-спутники, которые могут лежать рядом с миграциями и миграциями не являются.
|
||||
const COMPANION_FILE_RE = /\.(d|spec|test)\.ts$/;
|
||||
|
||||
export interface MigrationEntry {
|
||||
/** Путь относительно apps/api/src, с расширением .ts */
|
||||
file: string;
|
||||
className: string;
|
||||
}
|
||||
|
||||
export function fail(prefix: string, message: string): never {
|
||||
console.error(`[${prefix}] ОШИБКА: ${message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Объявление, а не стрелочная константа: сужение типов по never-возврату
|
||||
// (files после catch, timestampMatch после проверки) работает только для function.
|
||||
function failBuild(message: string): never {
|
||||
fail('buildDataSource', message);
|
||||
}
|
||||
|
||||
// Список каталогов миграций: любой apps/api/src/**/migrations.
|
||||
function findMigrationsDirs(dir: string): string[] {
|
||||
let entries: Dirent[];
|
||||
|
||||
try {
|
||||
entries = readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
failBuild(`не удалось прочитать директорию: ${dir}`);
|
||||
}
|
||||
|
||||
const found: string[] = [];
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory() || entry.name === 'node_modules') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fullPath = path.join(dir, entry.name);
|
||||
|
||||
if (entry.name === MIGRATIONS_DIR_NAME) {
|
||||
found.push(fullPath);
|
||||
continue;
|
||||
}
|
||||
|
||||
found.push(...findMigrationsDirs(fullPath));
|
||||
}
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
// Порядок — по timestamp из имени файла (возрастание): имя файла начинается ровно с
|
||||
// 13 цифр, поэтому лексикографическая сортировка совпадает с числовой. Одинаковые
|
||||
// имена файлов в разных модулях упорядочиваются по пути.
|
||||
export function readMigrations(): MigrationEntry[] {
|
||||
const migrationFiles = findMigrationsDirs(apiSrcDir)
|
||||
.flatMap((dir) =>
|
||||
readdirSync(dir, { withFileTypes: true })
|
||||
.filter((entry) => entry.isFile())
|
||||
.map((entry) => path.posix.join(path.relative(apiSrcDir, dir), entry.name))
|
||||
.filter((file) => file.endsWith('.ts') && !COMPANION_FILE_RE.test(file)),
|
||||
)
|
||||
.sort((a, b) => {
|
||||
const byName = path.posix.basename(a).localeCompare(path.posix.basename(b));
|
||||
|
||||
return byName !== 0 ? byName : a.localeCompare(b);
|
||||
});
|
||||
|
||||
// Каталогов migrations может не быть ни одного: проект может ещё не иметь
|
||||
// миграций. Тогда список пустой, а сборка не падает.
|
||||
|
||||
const entries = migrationFiles.map((file): MigrationEntry => {
|
||||
const timestampMatch = TIMESTAMP_PREFIX_RE.exec(path.posix.basename(file));
|
||||
|
||||
if (!timestampMatch) {
|
||||
failBuild(
|
||||
`имя файла "${file}" не начинается с 13-значного timestamp ` +
|
||||
'(ожидается формат "<13 цифр>-<name>.ts")',
|
||||
);
|
||||
}
|
||||
|
||||
const source = readFileSync(path.join(apiSrcDir, file), 'utf8');
|
||||
const classNames = [...source.matchAll(EXPORT_CLASS_RE)].map((match) => match[1]);
|
||||
|
||||
if (classNames.length === 0) {
|
||||
failBuild(`в файле "${file}" не найден "export class"`);
|
||||
}
|
||||
|
||||
// Брать первый попавшийся нельзя: TypeORM выводит timestamp из имени класса,
|
||||
// и вспомогательный экспорт выше миграции молча подменил бы порядок.
|
||||
if (classNames.length > 1) {
|
||||
failBuild(
|
||||
`в файле "${file}" найдено несколько "export class" (${classNames.join(', ')}); ` +
|
||||
'в файле миграции должен быть ровно один экспортируемый класс',
|
||||
);
|
||||
}
|
||||
|
||||
const className = classNames[0];
|
||||
|
||||
// Инвариант TypeORM: он игнорирует порядок массива и сортирует по
|
||||
// parseInt(className.substr(-13)). Если суффикс класса расходится с префиксом
|
||||
// файла, миграции применяются не в том порядке, а в таблице migrations
|
||||
// оказывается чужой timestamp.
|
||||
if (className.slice(-13) !== timestampMatch[1]) {
|
||||
failBuild(
|
||||
`в файле "${file}" класс "${className}" оканчивается на ` +
|
||||
`"${className.slice(-13)}", а имя файла — на "${timestampMatch[1]}"; ` +
|
||||
'TypeORM берёт timestamp из имени класса, суффиксы обязаны совпадать',
|
||||
);
|
||||
}
|
||||
|
||||
return { file, className };
|
||||
});
|
||||
|
||||
const seen = new Map<string, string>();
|
||||
|
||||
for (const entry of entries) {
|
||||
const duplicate = seen.get(entry.className);
|
||||
|
||||
if (duplicate) {
|
||||
failBuild(
|
||||
`класс "${entry.className}" объявлен дважды: "${duplicate}" и "${entry.file}"`,
|
||||
);
|
||||
}
|
||||
|
||||
seen.set(entry.className, entry.file);
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
function render(entries: MigrationEntry[]): string {
|
||||
if (entries.length === 0) {
|
||||
return `${HEADER}\n\nexport const migrations = [];\n`;
|
||||
}
|
||||
|
||||
const imports = entries
|
||||
.map(
|
||||
(entry) =>
|
||||
`import { ${entry.className} } from './${entry.file.slice(0, -'.ts'.length)}';`,
|
||||
)
|
||||
.join('\n');
|
||||
|
||||
const list = entries.map((entry) => ` ${entry.className},`).join('\n');
|
||||
|
||||
return `${HEADER}\n\n${imports}\n\nexport const migrations = [\n${list}\n];\n`;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const entries = readMigrations();
|
||||
const prettierConfig = await resolveConfig(outputFile);
|
||||
|
||||
const formatted = await format(render(entries), {
|
||||
...prettierConfig,
|
||||
filepath: outputFile,
|
||||
parser: 'typescript',
|
||||
});
|
||||
|
||||
const relativeOutput = path.relative(workspaceRoot, outputFile);
|
||||
const current = existsSync(outputFile) ? readFileSync(outputFile, 'utf8') : null;
|
||||
const upToDate = current === formatted;
|
||||
|
||||
console.log(`[buildDataSource] миграций найдено: ${entries.length}`);
|
||||
|
||||
// --check ничего не пишет и падает при расхождении. Сравнение идёт с тем же
|
||||
// отформатированным текстом, что и запись, поэтому CI не нужно поднимать
|
||||
// git diff и отличать «список устарел» от «git не смог прочитать репозиторий».
|
||||
if (process.argv.includes('--check')) {
|
||||
if (!upToDate) {
|
||||
failBuild(
|
||||
`${relativeOutput} расходится со списком файлов миграций. ` +
|
||||
'Перегенерируйте: yarn nx run api:db-migrations-list — и закоммитьте результат',
|
||||
);
|
||||
}
|
||||
|
||||
console.log(`[buildDataSource] актуален: ${relativeOutput}`);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Пишем только при реальном изменении: build зависит от этого таргета, а
|
||||
// api:serve следит за src/ — перезапись с тем же содержимым дёргает mtime
|
||||
// и загоняет watch-режим в бесконечный цикл пересборок.
|
||||
if (upToDate) {
|
||||
console.log(`[buildDataSource] без изменений: ${relativeOutput}`);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
writeFileSync(outputFile, formatted, 'utf8');
|
||||
|
||||
console.log(`[buildDataSource] записано: ${relativeOutput}`);
|
||||
}
|
||||
|
||||
// Модуль импортируется из tools/checkDataSource.ts ради readMigrations(),
|
||||
// поэтому генерация запускается только при прямом вызове файла.
|
||||
if (require.main === module) {
|
||||
main().catch((error) => {
|
||||
failBuild(error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// Проверка собранного артефакта apps/api/dist/data-source.js.
|
||||
// Запускается после `nx run api:build` в CI (ci.yaml и production.yaml).
|
||||
//
|
||||
// Проверяем не «список непустой», а то, что состав миграций в собранном бандле
|
||||
// посимвольно совпадает со списком, который даёт генератор по файлам на диске.
|
||||
// Ожидаемый список берётся вызовом readMigrations() из tools/buildDataSource.ts,
|
||||
// а не разбором сгенерированного им же файла: правила фильтрации и валидации
|
||||
// имён живут в одном месте (там же проверяется инвариант TypeORM
|
||||
// parseInt(className.substr(-13)) === префикс имени файла).
|
||||
|
||||
import * as path from 'path';
|
||||
|
||||
import { fail, readMigrations, workspaceRoot } from './buildDataSource';
|
||||
|
||||
const DATA_SOURCE_FILE = path.join(workspaceRoot, 'apps', 'api', 'dist', 'data-source.js');
|
||||
|
||||
// Объявление, а не стрелочная константа: сужение типов по never-возврату
|
||||
// (loaded после catch) работает только для function.
|
||||
function failCheck(message: string): never {
|
||||
fail('checkDataSource', message);
|
||||
}
|
||||
|
||||
function loadDataSource(): { options: { migrations?: unknown } } {
|
||||
let loaded;
|
||||
|
||||
try {
|
||||
loaded = require(DATA_SOURCE_FILE);
|
||||
} catch (error) {
|
||||
failCheck(
|
||||
`не удалось загрузить ${DATA_SOURCE_FILE}: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Бандл может отдать как сам DataSource, так и { default: DataSource } —
|
||||
// зависит от output.library.export, поэтому разворачиваем оба варианта.
|
||||
const dataSource = loaded?.default ?? loaded;
|
||||
|
||||
// Проверяем поведение, а не имя конструктора: имя пережило бы только
|
||||
// отключённую минификацию, а поведение — это то, чем пользуется typeorm CLI.
|
||||
if (typeof dataSource?.initialize !== 'function' || typeof dataSource.options !== 'object') {
|
||||
failCheck(`ожидался DataSource, получено: ${JSON.stringify(dataSource)}`);
|
||||
}
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
function main(): void {
|
||||
const { migrations } = loadDataSource().options;
|
||||
const expected = readMigrations().map((entry) => entry.className);
|
||||
// Элементы списка — классы миграций; у не-класса name окажется undefined и
|
||||
// расхождение выведется в том же диффе, что и любое другое.
|
||||
const actual = Array.isArray(migrations)
|
||||
? migrations.map((migration) => (migration as { name?: string })?.name)
|
||||
: [migrations];
|
||||
|
||||
if (actual.join(',') !== expected.join(',')) {
|
||||
failCheck(
|
||||
'состав миграций в бандле расходится с файлами на диске.\n' +
|
||||
` в бандле (${actual.length}): ${actual.join(', ')}\n` +
|
||||
` на диске (${expected.length}): ${expected.join(', ')}\n` +
|
||||
' перегенерируйте список (yarn nx run api:db-migrations-list) и пересоберите api',
|
||||
);
|
||||
}
|
||||
|
||||
console.log(
|
||||
`[checkDataSource] OK: миграций в бандле ${expected.length}, ` +
|
||||
'состав совпадает с файлами миграций',
|
||||
);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,205 @@
|
||||
import { readdir, readFile } from 'fs/promises';
|
||||
import path, { resolve } from 'path';
|
||||
|
||||
import { config } from 'dotenv';
|
||||
import { omit } from 'lodash';
|
||||
import { Pool, PoolClient } from 'pg';
|
||||
|
||||
interface SnapshotEntity {
|
||||
table: string;
|
||||
arrayFields?: string[];
|
||||
omitFields?: string[];
|
||||
updateExisting?: boolean;
|
||||
}
|
||||
|
||||
export async function applySnapshot(
|
||||
snapshot: Record<string, Array<object>>,
|
||||
connection: PoolClient,
|
||||
) {
|
||||
const entities: SnapshotEntity[] = [
|
||||
{ table: 'admin_settings' },
|
||||
{ table: 'users' },
|
||||
{ table: 'projects' },
|
||||
{ table: 'canonical_brand_data' },
|
||||
{ table: 'entity_audit_logs' },
|
||||
{ table: 'entity_completeness_tracking' },
|
||||
{ table: 'entity_facts' },
|
||||
{ table: 'entity_home_pages' },
|
||||
{ table: 'external_connectors' },
|
||||
{ table: 'external_profiles' },
|
||||
{ table: 'file' },
|
||||
{ table: 'json_ld_schemas' },
|
||||
{ table: 'migration_1772363000000_default_user_role_users' },
|
||||
{ table: 'nap_consistency_scores' },
|
||||
{ table: 'project_entities' },
|
||||
{ table: 'project_entity_data' },
|
||||
{ table: 'project_licenses' },
|
||||
{ table: 'project_members' },
|
||||
{ table: 'project_metrics' },
|
||||
{ table: 'project_products' },
|
||||
{ table: 'project_team_members' },
|
||||
{ table: 'roles' },
|
||||
{ table: 'sync_logs' },
|
||||
{ table: 'user_roles' },
|
||||
{ table: 'website_checks' },
|
||||
{ table: 'wikidata_edit_queue' },
|
||||
{ table: 'wikidata_entities' },
|
||||
{ table: 'subscription_plans' },
|
||||
{ table: 'brand_questions', arrayFields: ['questions'] },
|
||||
{ table: 'public_metric_requests', arrayFields: ['keywords', 'modelsUsed'] },
|
||||
];
|
||||
|
||||
await nuke(entities, connection);
|
||||
|
||||
if (!entities) {
|
||||
console.log('no entities');
|
||||
}
|
||||
if (!snapshot) {
|
||||
console.log('no snaphot');
|
||||
}
|
||||
for (const updateTable of entities.map(genUpdateTable)) {
|
||||
await updateTable(snapshot, connection);
|
||||
}
|
||||
}
|
||||
|
||||
function genUpdateTable(snapshotEntity: SnapshotEntity) {
|
||||
let processRow = (row: object) => row;
|
||||
const save = snapshotEntity.updateExisting ? update : insert;
|
||||
|
||||
if ('omitFields' in snapshotEntity && snapshotEntity.omitFields?.length) {
|
||||
processRow = (row: object) => omit(row, snapshotEntity.omitFields!);
|
||||
}
|
||||
|
||||
return async (snapshot: Record<string, Array<object>>, connection: PoolClient) => {
|
||||
const data = snapshot[snapshotEntity.table].map(processRow);
|
||||
const ids = snapshot[snapshotEntity.table]
|
||||
.map((row: any): number => row?.id)
|
||||
.filter(Boolean);
|
||||
const lastId = Math.max(...ids);
|
||||
|
||||
if (!data) {
|
||||
return;
|
||||
}
|
||||
|
||||
await save(snapshotEntity, data, connection);
|
||||
|
||||
if (Number.isFinite(lastId)) {
|
||||
await connection.query(
|
||||
`ALTER SEQUENCE IF EXISTS ${snapshotEntity.table}_id_seq RESTART WITH ${lastId + 1}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function insert(entity: SnapshotEntity, rows: object[], connection: PoolClient) {
|
||||
if (!rows.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const keys = Object.keys(rows[0]).map((column) => `"${column}"`);
|
||||
const values = rows.map((row) => serializeObjects(row, entity.arrayFields));
|
||||
const placeholders = values.map(wrapReturnedInBrackets(genRowPlaceholders));
|
||||
|
||||
const query = `INSERT INTO ${entity.table} (${keys}) VALUES ${placeholders}`;
|
||||
|
||||
return connection.query(query, values.flat());
|
||||
}
|
||||
|
||||
async function update(entity: SnapshotEntity, rows: object[], connection: PoolClient) {
|
||||
if (!rows.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const keys = Object.keys(rows[0]).map((column) => `"${column}"`);
|
||||
|
||||
const promises = rows.map((row: any) => {
|
||||
const placeholders = genRowPlaceholders(keys).map((val, idx) => keys[idx] + '=' + val);
|
||||
const values = serializeObjects(row, entity.arrayFields);
|
||||
|
||||
return connection.query(
|
||||
`UPDATE ${entity.table} SET ${placeholders} WHERE id=${row.id};`,
|
||||
values,
|
||||
);
|
||||
});
|
||||
|
||||
return Promise.all(promises);
|
||||
}
|
||||
|
||||
function wrapReturnedInBrackets(fn: (...args: any[]) => any) {
|
||||
return (...args: any) => '(' + fn(...args) + ')';
|
||||
}
|
||||
|
||||
function genRowPlaceholders(row: any[], offsetByRows?: number) {
|
||||
const rowIdx = offsetByRows || 0;
|
||||
|
||||
return row.map((_, colIdx) => row.length * rowIdx + colIdx + 1).map((idx) => '$' + idx);
|
||||
}
|
||||
|
||||
function serializeObjects(row: any, leaveAsIs: string[] = []) {
|
||||
return Object.entries(row).map(([key, value]) => {
|
||||
if (leaveAsIs.includes(key)) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (typeof value !== 'object' || value === null) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return JSON.stringify(value);
|
||||
});
|
||||
}
|
||||
|
||||
async function nuke(entities: SnapshotEntity[], connection: PoolClient) {
|
||||
const tables = new Set(entities.map(({ table }) => table));
|
||||
|
||||
return connection
|
||||
.query(`TRUNCATE TABLE ${[...tables].join(',')} RESTART IDENTITY CASCADE;`)
|
||||
.catch(console.error);
|
||||
}
|
||||
|
||||
export async function readSnapshot(basePath: string) {
|
||||
const files = await readdir(basePath);
|
||||
|
||||
const entries = await Promise.all(
|
||||
files.map(async (filename) => {
|
||||
const tableName = filename.split('.').slice(0, -1).join('.');
|
||||
|
||||
const text = await readFile(resolve(basePath, filename), { encoding: 'utf8' });
|
||||
const rows = JSON.parse(text);
|
||||
|
||||
const entry = [tableName, rows];
|
||||
|
||||
return entry;
|
||||
}),
|
||||
);
|
||||
|
||||
return Object.fromEntries(entries) as Record<string, Array<object>>;
|
||||
}
|
||||
|
||||
const nodeEnv = process.env.NODE_ENV || 'production';
|
||||
config({ path: path.resolve(process.cwd(), `.env.${nodeEnv}`) });
|
||||
config({ path: path.resolve(process.cwd(), '.env') });
|
||||
|
||||
const pool = new Pool({
|
||||
host: process.env.POSTGRES_HOST,
|
||||
port: +process.env.POSTGRES_PORT!,
|
||||
user: process.env.POSTGRES_USER,
|
||||
password: process.env.POSTGRES_PASSWORD,
|
||||
database: process.env.POSTGRES_DB,
|
||||
});
|
||||
|
||||
const snapshotDir = path.join(__dirname, '../db-snapshot');
|
||||
|
||||
async function main() {
|
||||
const db = await pool.connect();
|
||||
console.log('ДБ подключена');
|
||||
|
||||
const snapshot = await readSnapshot(snapshotDir);
|
||||
await applySnapshot(snapshot, db);
|
||||
|
||||
console.log('Снимок применён к базе данных');
|
||||
db.release();
|
||||
await pool.end();
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,91 @@
|
||||
import { access, mkdir, rm, writeFile } from 'fs/promises';
|
||||
import path from 'path';
|
||||
|
||||
import { config } from 'dotenv';
|
||||
import { Pool, types } from 'pg';
|
||||
|
||||
const nodeEnv = process.env.NODE_ENV || 'production';
|
||||
config({ path: path.resolve(process.cwd(), `.env.${nodeEnv}`) });
|
||||
config({ path: path.resolve(process.cwd(), '.env') });
|
||||
|
||||
const pool = new Pool({
|
||||
host: process.env.POSTGRES_HOST,
|
||||
port: +process.env.POSTGRES_PORT!,
|
||||
user: process.env.POSTGRES_USER,
|
||||
password: process.env.POSTGRES_PASSWORD,
|
||||
database: process.env.POSTGRES_DB,
|
||||
});
|
||||
|
||||
const snapshotDir = path.join(__dirname, '../db-snapshot');
|
||||
|
||||
const excludedTables = ['migrations', 'oauth_providers'];
|
||||
|
||||
// так как в ДБ используются поля без часового пояса, а по умолчанию pg будет ставить UTC
|
||||
function disableTZProcessing() {
|
||||
types.setTypeParser(1114, function (stringValue) {
|
||||
return stringValue;
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
disableTZProcessing();
|
||||
|
||||
const db = await pool.connect();
|
||||
|
||||
console.log('ДБ подключена');
|
||||
await db.query("SET timezone TO 'GMT';");
|
||||
|
||||
const tables = await db
|
||||
.query(
|
||||
`
|
||||
SELECT c.relname AS tablename, (array_agg(a.attname))[1] AS key
|
||||
FROM pg_index i
|
||||
JOIN pg_class c ON c.oid = i.indrelid
|
||||
JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY(i.indkey)
|
||||
WHERE i.indisprimary
|
||||
AND n.nspname = 'public'
|
||||
AND c.relname NOT IN (${excludedTables.map(wrapInQuotes).join(',')})
|
||||
GROUP BY c.relname
|
||||
ORDER BY c.relname;
|
||||
`,
|
||||
)
|
||||
.then((response): { tablename: string; key: string }[] => response.rows);
|
||||
|
||||
const promises = tables.map(async (table) => {
|
||||
const data = await db.query(`SELECT * FROM ${table.tablename} ORDER BY "${table.key}"`);
|
||||
|
||||
return { ...table, rows: data.rows };
|
||||
});
|
||||
|
||||
const entries = await Promise.all(promises);
|
||||
|
||||
await access(snapshotDir).then(
|
||||
async () => {
|
||||
await rm(snapshotDir, { recursive: true });
|
||||
},
|
||||
() => {},
|
||||
);
|
||||
|
||||
await mkdir(snapshotDir, { recursive: true });
|
||||
|
||||
const report = await Promise.all(
|
||||
entries.map(async (table) =>
|
||||
writeFile(
|
||||
path.join(snapshotDir, table.tablename + '.json'),
|
||||
JSON.stringify(table.rows, null, 4) + '\n',
|
||||
'utf8',
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
console.log('Сохранено таблиц: `\x1b[0;32m' + report.length + '\x1b[0m`');
|
||||
db.release();
|
||||
await pool.end();
|
||||
}
|
||||
|
||||
function wrapInQuotes(text: string) {
|
||||
return "'" + text + "'";
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"declarationMap": true,
|
||||
"emitDeclarationOnly": true,
|
||||
"importHelpers": true,
|
||||
"isolatedModules": true,
|
||||
"lib": [
|
||||
"es2022"
|
||||
],
|
||||
"module": "nodenext",
|
||||
"moduleResolution": "nodenext",
|
||||
"noEmitOnError": true,
|
||||
"skipLibCheck": true,
|
||||
"target": "es2022",
|
||||
"baseUrl": "./",
|
||||
"customConditions": [
|
||||
"@it-smi/source"
|
||||
],
|
||||
"paths": {
|
||||
"@it-smi/api/*": [
|
||||
"apps/api/src/*"
|
||||
],
|
||||
"@it-smi/web/*": [
|
||||
"apps/web/src/*"
|
||||
]
|
||||
},
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"useUnknownInCatchVariables": false,
|
||||
"strictPropertyInitialization": false,
|
||||
|
||||
"noImplicitAny": true,
|
||||
"noImplicitOverride": true,
|
||||
"noImplicitReturns": true,
|
||||
"noUnusedLocals": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "./tsconfig.base.json",
|
||||
"compileOnSave": false,
|
||||
"files": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./apps/web"
|
||||
},
|
||||
{
|
||||
"path": "./apps/api-e2e"
|
||||
},
|
||||
{
|
||||
"path": "./apps/api"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export default ['**/vite.config.{mjs,js,ts,mts}', '**/vitest.config.{mjs,js,ts,mts}'];
|
||||
Reference in new issue
Block a user