feat: обновление конфигурации проекта с использованием TypeScript и улучшение обработки ошибок
- Переписаны основные файлы сервера с JavaScript на TypeScript. - Добавлен новый обработчик ошибок с логированием в базу данных. - Обновлен Dockerfile для поддержки сборки TypeScript. - Изменены настройки окружения для MongoDB в docker-compose. - Удалены устаревшие файлы и добавлены новые модели и утилиты для работы с MongoDB. - Обновлены зависимости в package.json и package-lock.json.
This commit is contained in:
34
Dockerfile
34
Dockerfile
@@ -1,16 +1,38 @@
|
||||
FROM node:20
|
||||
FROM node:22 AS builder
|
||||
|
||||
WORKDIR /usr/src/app/
|
||||
|
||||
# Сначала копируем только файлы, необходимые для установки зависимостей
|
||||
COPY ./package.json /usr/src/app/package.json
|
||||
COPY ./package-lock.json /usr/src/app/package-lock.json
|
||||
|
||||
# Устанавливаем все зависимости
|
||||
RUN npm ci
|
||||
|
||||
# Затем копируем исходный код проекта и файлы конфигурации
|
||||
COPY ./tsconfig.json /usr/src/app/tsconfig.json
|
||||
COPY ./server /usr/src/app/server
|
||||
|
||||
# Сборка проекта
|
||||
RUN npm run build
|
||||
|
||||
# Вторая стадия - рабочий образ
|
||||
FROM node:22
|
||||
|
||||
RUN mkdir -p /usr/src/app/server/log/
|
||||
WORKDIR /usr/src/app/
|
||||
|
||||
COPY ./server /usr/src/app/server
|
||||
# Копирование только package.json/package-lock.json для продакшн зависимостей
|
||||
COPY ./package.json /usr/src/app/package.json
|
||||
COPY ./package-lock.json /usr/src/app/package-lock.json
|
||||
COPY ./.serverrc.js /usr/src/app/.serverrc.js
|
||||
# COPY ./.env /usr/src/app/.env
|
||||
|
||||
# RUN npm i --omit=dev
|
||||
RUN npm ci
|
||||
# Установка только продакшн зависимостей
|
||||
RUN npm ci --production
|
||||
|
||||
# Копирование собранного приложения из билдера
|
||||
COPY --from=builder /usr/src/app/dist /usr/src/app/dist
|
||||
COPY --from=builder /usr/src/app/server /usr/src/app/server
|
||||
|
||||
EXPOSE 8044
|
||||
|
||||
CMD ["npm", "run", "up:prod"]
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
#!/bin/sh
|
||||
|
||||
docker stop ms-mongo
|
||||
docker volume remove ms_volume
|
||||
docker volume create ms_volume
|
||||
docker run --rm -v ms_volume:/data/db --name ms-mongo -p 27017:27017 -d mongo:8.0.3
|
||||
docker volume remove ms_volume8
|
||||
docker volume create ms_volume8
|
||||
docker run --rm \
|
||||
-v ms_volume8:/data/db \
|
||||
--name ms-mongo \
|
||||
-p 27018:27017 \
|
||||
-e MONGO_INITDB_ROOT_USERNAME=qqq \
|
||||
-e MONGO_INITDB_ROOT_PASSWORD=qqq \
|
||||
-d mongo:8.0.3
|
||||
|
||||
@@ -10,10 +10,12 @@ services:
|
||||
volumes:
|
||||
- ms_volume8:/data/db
|
||||
restart: always
|
||||
# ports:
|
||||
# - 27017:27017
|
||||
environment:
|
||||
- MONGO_INITDB_ROOT_USERNAME=${MONGO_INITDB_ROOT_USERNAME}
|
||||
- MONGO_INITDB_ROOT_PASSWORD=${MONGO_INITDB_ROOT_PASSWORD}
|
||||
ports:
|
||||
- 27018:27017
|
||||
multy-stubs:
|
||||
# build: .
|
||||
image: bro.js/ms/bh:$TAG
|
||||
restart: always
|
||||
volumes:
|
||||
@@ -22,4 +24,4 @@ services:
|
||||
- 8044:8044
|
||||
environment:
|
||||
- TZ=Europe/Moscow
|
||||
- MONGO_ADDR=mongodb
|
||||
- MONGO_ADDR=mongodb://${MONGO_INITDB_ROOT_USERNAME}:${MONGO_INITDB_ROOT_PASSWORD}@mongodb:27017
|
||||
@@ -4,7 +4,7 @@ import pluginJs from "@eslint/js";
|
||||
|
||||
export default [
|
||||
{ ignores: ['server/routers/old/*'] },
|
||||
{ files: ["**/*.js"], languageOptions: { sourceType: "commonjs" } },
|
||||
{ files: ["**/*.js"], languageOptions: { } },
|
||||
{ languageOptions: { globals: globals.node } },
|
||||
pluginJs.configs.recommended,
|
||||
{
|
||||
|
||||
291
package-lock.json
generated
291
package-lock.json
generated
@@ -41,7 +41,9 @@
|
||||
"jest": "^29.7.0",
|
||||
"mockingoose": "^2.16.2",
|
||||
"nodemon": "3.1.9",
|
||||
"supertest": "^7.0.0"
|
||||
"supertest": "^7.0.0",
|
||||
"ts-node-dev": "2.0.0",
|
||||
"typescript": "5.7.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@ai-sdk/provider": {
|
||||
@@ -852,6 +854,30 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@cspotcode/source-map-support": {
|
||||
"version": "0.8.1",
|
||||
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
|
||||
"integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jridgewell/trace-mapping": "0.3.9"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@cspotcode/source-map-support/node_modules/@jridgewell/trace-mapping": {
|
||||
"version": "0.3.9",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz",
|
||||
"integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jridgewell/resolve-uri": "^3.0.3",
|
||||
"@jridgewell/sourcemap-codec": "^1.4.10"
|
||||
}
|
||||
},
|
||||
"node_modules/@csstools/color-helpers": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.0.1.tgz",
|
||||
@@ -1747,6 +1773,34 @@
|
||||
"resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.0.tgz",
|
||||
"integrity": "sha512-+9jVqKhRSpsc591z5vX+X5Yyw+he/HCB4iQ/RYxw35CEPaY1gnsNE43nf9n9AaYjAQrTiI/mOwKUKdUs9vf7Xg=="
|
||||
},
|
||||
"node_modules/@tsconfig/node10": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz",
|
||||
"integrity": "sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@tsconfig/node12": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz",
|
||||
"integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@tsconfig/node14": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz",
|
||||
"integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@tsconfig/node16": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz",
|
||||
"integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/babel__core": {
|
||||
"version": "7.20.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
|
||||
@@ -1882,6 +1936,20 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/strip-bom": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/strip-bom/-/strip-bom-3.0.0.tgz",
|
||||
"integrity": "sha512-xevGOReSYGM7g/kUBZzPqCrR/KYAo+F0yiPc85WFTJa0MSLtyFTVTU6cJu/aV4mid7IffDIWqo69THF2o4JiEQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/strip-json-comments": {
|
||||
"version": "0.0.30",
|
||||
"resolved": "https://registry.npmjs.org/@types/strip-json-comments/-/strip-json-comments-0.0.30.tgz",
|
||||
"integrity": "sha512-7NQmHra/JILCd1QqpSzl8+mJRc8ZHz3uDm8YV1Ks9IhK0epEiTw8aIErbvH9PI+6XbqhyIQy3462nEsn7UVzjQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/webidl-conversions": {
|
||||
"version": "7.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz",
|
||||
@@ -1954,6 +2022,19 @@
|
||||
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/acorn-walk": {
|
||||
"version": "8.3.4",
|
||||
"resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz",
|
||||
"integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"acorn": "^8.11.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/agent-base": {
|
||||
"version": "6.0.2",
|
||||
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
|
||||
@@ -2121,6 +2202,13 @@
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/arg": {
|
||||
"version": "4.1.3",
|
||||
"resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz",
|
||||
"integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/argparse": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
|
||||
@@ -2846,6 +2934,13 @@
|
||||
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/create-require": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz",
|
||||
"integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/cross-env": {
|
||||
"version": "7.0.3",
|
||||
"resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz",
|
||||
@@ -3062,6 +3157,16 @@
|
||||
"wrappy": "1"
|
||||
}
|
||||
},
|
||||
"node_modules/diff": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz",
|
||||
"integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"node": ">=0.3.1"
|
||||
}
|
||||
},
|
||||
"node_modules/diff-match-patch": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/diff-match-patch/-/diff-match-patch-1.0.5.tgz",
|
||||
@@ -3104,6 +3209,16 @@
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/dynamic-dedupe": {
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://registry.npmjs.org/dynamic-dedupe/-/dynamic-dedupe-0.3.0.tgz",
|
||||
"integrity": "sha512-ssuANeD+z97meYOqd50e04Ze5qp4bPqo8cCkI4TRjZkzAUgIDTrXV1R8QCdINpiI+hw14+rYazvTRdQrz0/rFQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"xtend": "^4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ecdsa-sig-formatter": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
|
||||
@@ -5774,6 +5889,13 @@
|
||||
"semver": "bin/semver.js"
|
||||
}
|
||||
},
|
||||
"node_modules/make-error": {
|
||||
"version": "1.3.6",
|
||||
"resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",
|
||||
"integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/makeerror": {
|
||||
"version": "1.0.12",
|
||||
"resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz",
|
||||
@@ -7876,6 +7998,142 @@
|
||||
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
|
||||
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
|
||||
},
|
||||
"node_modules/tree-kill": {
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",
|
||||
"integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"tree-kill": "cli.js"
|
||||
}
|
||||
},
|
||||
"node_modules/ts-node": {
|
||||
"version": "10.9.2",
|
||||
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz",
|
||||
"integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@cspotcode/source-map-support": "^0.8.0",
|
||||
"@tsconfig/node10": "^1.0.7",
|
||||
"@tsconfig/node12": "^1.0.7",
|
||||
"@tsconfig/node14": "^1.0.0",
|
||||
"@tsconfig/node16": "^1.0.2",
|
||||
"acorn": "^8.4.1",
|
||||
"acorn-walk": "^8.1.1",
|
||||
"arg": "^4.1.0",
|
||||
"create-require": "^1.1.0",
|
||||
"diff": "^4.0.1",
|
||||
"make-error": "^1.1.1",
|
||||
"v8-compile-cache-lib": "^3.0.1",
|
||||
"yn": "3.1.1"
|
||||
},
|
||||
"bin": {
|
||||
"ts-node": "dist/bin.js",
|
||||
"ts-node-cwd": "dist/bin-cwd.js",
|
||||
"ts-node-esm": "dist/bin-esm.js",
|
||||
"ts-node-script": "dist/bin-script.js",
|
||||
"ts-node-transpile-only": "dist/bin-transpile.js",
|
||||
"ts-script": "dist/bin-script-deprecated.js"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@swc/core": ">=1.2.50",
|
||||
"@swc/wasm": ">=1.2.50",
|
||||
"@types/node": "*",
|
||||
"typescript": ">=2.7"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@swc/core": {
|
||||
"optional": true
|
||||
},
|
||||
"@swc/wasm": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/ts-node-dev": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ts-node-dev/-/ts-node-dev-2.0.0.tgz",
|
||||
"integrity": "sha512-ywMrhCfH6M75yftYvrvNarLEY+SUXtUvU8/0Z6llrHQVBx12GiFk5sStF8UdfE/yfzk9IAq7O5EEbTQsxlBI8w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"chokidar": "^3.5.1",
|
||||
"dynamic-dedupe": "^0.3.0",
|
||||
"minimist": "^1.2.6",
|
||||
"mkdirp": "^1.0.4",
|
||||
"resolve": "^1.0.0",
|
||||
"rimraf": "^2.6.1",
|
||||
"source-map-support": "^0.5.12",
|
||||
"tree-kill": "^1.2.2",
|
||||
"ts-node": "^10.4.0",
|
||||
"tsconfig": "^7.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"ts-node-dev": "lib/bin.js",
|
||||
"tsnd": "lib/bin.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.8.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"node-notifier": "*",
|
||||
"typescript": "*"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"node-notifier": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/ts-node-dev/node_modules/rimraf": {
|
||||
"version": "2.7.1",
|
||||
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz",
|
||||
"integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==",
|
||||
"deprecated": "Rimraf versions prior to v4 are no longer supported",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"glob": "^7.1.3"
|
||||
},
|
||||
"bin": {
|
||||
"rimraf": "bin.js"
|
||||
}
|
||||
},
|
||||
"node_modules/tsconfig": {
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmjs.org/tsconfig/-/tsconfig-7.0.0.tgz",
|
||||
"integrity": "sha512-vZXmzPrL+EmC4T/4rVlT2jNVMWCi/O4DIiSj3UHg1OE5kCKbk4mfrXc6dZksLgRM/TZlKnousKH9bbTazUWRRw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/strip-bom": "^3.0.0",
|
||||
"@types/strip-json-comments": "0.0.30",
|
||||
"strip-bom": "^3.0.0",
|
||||
"strip-json-comments": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tsconfig/node_modules/strip-bom": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz",
|
||||
"integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/tsconfig/node_modules/strip-json-comments": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
|
||||
"integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/type-check": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
|
||||
@@ -7930,6 +8188,20 @@
|
||||
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.7.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz",
|
||||
"integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/uid-safe": {
|
||||
"version": "2.1.5",
|
||||
"resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz",
|
||||
@@ -8037,6 +8309,13 @@
|
||||
"uuid": "dist/esm/bin/uuid"
|
||||
}
|
||||
},
|
||||
"node_modules/v8-compile-cache-lib": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",
|
||||
"integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/v8-to-istanbul": {
|
||||
"version": "9.3.0",
|
||||
"resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz",
|
||||
@@ -8286,6 +8565,16 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/yn": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",
|
||||
"integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/yocto-queue": {
|
||||
"version": "0.1.0",
|
||||
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
|
||||
|
||||
16
package.json
16
package.json
@@ -2,14 +2,12 @@
|
||||
"name": "multi-stub",
|
||||
"version": "1.2.1",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"main": "server/index.ts",
|
||||
"type": "commonjs",
|
||||
"scripts": {
|
||||
"start": "cross-env PORT=8033 npx nodemon ./server",
|
||||
"up:prod": "cross-env NODE_ENV=\"production\" node ./server",
|
||||
"deploy:d:stop": "docker compose down",
|
||||
"deploy:d:build": "docker compose build",
|
||||
"deploy:d:up": "docker compose up -d",
|
||||
"redeploy": "npm run deploy:d:stop && npm run deploy:d:build && npm run deploy:d:up",
|
||||
"start": "cross-env NODE_ENV=\"development\" ts-node-dev .",
|
||||
"build": "tsc",
|
||||
"up:prod": "node dist/server/index.js",
|
||||
"eslint": "npx eslint ./server",
|
||||
"eslint:fix": "npx eslint ./server --fix",
|
||||
"test": "jest"
|
||||
@@ -55,6 +53,8 @@
|
||||
"jest": "^29.7.0",
|
||||
"mockingoose": "^2.16.2",
|
||||
"nodemon": "3.1.9",
|
||||
"supertest": "^7.0.0"
|
||||
"supertest": "^7.0.0",
|
||||
"ts-node-dev": "2.0.0",
|
||||
"typescript": "5.7.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
const noToken = 'No authorization token was found'
|
||||
|
||||
module.exports = (err, req, res, next) => {
|
||||
if (err.message === noToken) {
|
||||
res.status(400).send({
|
||||
success: false, error: 'Токен авторизации не найден',
|
||||
})
|
||||
}
|
||||
|
||||
res.status(400).send({
|
||||
success: false, error: err.message || 'Что-то пошло не так',
|
||||
})
|
||||
}
|
||||
28
server/error.ts
Normal file
28
server/error.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { ErrorLog } from './models/ErrorLog'
|
||||
|
||||
const noToken = 'No authorization token was found'
|
||||
|
||||
export const errorHandler = (err, req, res, next) => {
|
||||
// Сохраняем ошибку в базу данных
|
||||
const errorLog = new ErrorLog({
|
||||
message: err.message || 'Неизвестная ошибка',
|
||||
stack: err.stack,
|
||||
path: req.path,
|
||||
method: req.method,
|
||||
query: req.query,
|
||||
body: req.body
|
||||
})
|
||||
|
||||
errorLog.save()
|
||||
.catch(saveErr => console.error('Ошибка при сохранении лога ошибки:', saveErr))
|
||||
|
||||
if (err.message === noToken) {
|
||||
res.status(400).send({
|
||||
success: false, error: 'Токен авторизации не найден',
|
||||
})
|
||||
}
|
||||
|
||||
res.status(400).send({
|
||||
success: false, error: err.message || 'Что-то пошло не так',
|
||||
})
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
const express = require("express")
|
||||
const bodyParser = require("body-parser")
|
||||
const cookieParser = require("cookie-parser")
|
||||
const session = require("express-session")
|
||||
const morgan = require("morgan")
|
||||
const path = require("path")
|
||||
const rfs = require("rotating-file-stream")
|
||||
|
||||
const app = express()
|
||||
require("dotenv").config()
|
||||
exports.app = app
|
||||
|
||||
const accessLogStream = rfs.createStream("access.log", {
|
||||
size: "10M",
|
||||
interval: "1d",
|
||||
compress: "gzip",
|
||||
path: path.join(__dirname, "log"),
|
||||
})
|
||||
|
||||
const errorLogStream = rfs.createStream("error.log", {
|
||||
size: "10M",
|
||||
interval: "1d",
|
||||
compress: "gzip",
|
||||
path: path.join(__dirname, "log"),
|
||||
})
|
||||
|
||||
const config = require("../.serverrc")
|
||||
const { setIo } = require("./io")
|
||||
|
||||
app.use(cookieParser())
|
||||
app.use(
|
||||
morgan("combined", {
|
||||
stream: accessLogStream,
|
||||
skip: function (req, res) {
|
||||
return res.statusCode >= 400
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
// log all requests to access.log
|
||||
app.use(
|
||||
morgan("combined", {
|
||||
stream: errorLogStream,
|
||||
skip: function (req, res) {
|
||||
console.log('statusCode', res.statusCode, res.statusCode <= 400)
|
||||
return res.statusCode < 400
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
const server = setIo(app)
|
||||
|
||||
const sess = {
|
||||
secret: "super-secret-key",
|
||||
resave: true,
|
||||
saveUninitialized: true,
|
||||
cookie: {},
|
||||
}
|
||||
if (app.get("env") === "production") {
|
||||
app.set("trust proxy", 1)
|
||||
sess.cookie.secure = true
|
||||
}
|
||||
app.use(session(sess))
|
||||
|
||||
app.use(
|
||||
bodyParser.json({
|
||||
limit: "50mb",
|
||||
})
|
||||
)
|
||||
app.use(
|
||||
bodyParser.urlencoded({
|
||||
limit: "50mb",
|
||||
extended: true,
|
||||
})
|
||||
)
|
||||
app.use(require("./root"))
|
||||
|
||||
/**
|
||||
* Добавляйте сюда свои routers.
|
||||
*/
|
||||
app.use("/kfu-m-24-1", require("./routers/kfu-m-24-1"))
|
||||
app.use("/epja-2024-1", require("./routers/epja-2024-1"))
|
||||
app.use("/v1/todo", require("./routers/todo"))
|
||||
app.use("/dogsitters-finder", require("./routers/dogsitters-finder"))
|
||||
app.use("/kazan-explore", require("./routers/kazan-explore"))
|
||||
app.use("/edateam", require("./routers/edateam-legacy"))
|
||||
app.use("/dry-wash", require("./routers/dry-wash"))
|
||||
app.use("/freetracker", require("./routers/freetracker"))
|
||||
app.use("/dhs-testing", require("./routers/dhs-testing"))
|
||||
app.use("/gamehub", require("./routers/gamehub"))
|
||||
app.use("/esc", require("./routers/esc"))
|
||||
app.use('/connectme', require('./routers/connectme'))
|
||||
app.use('/questioneer', require('./routers/questioneer'))
|
||||
|
||||
app.use(require("./error"))
|
||||
|
||||
server.listen(config.port, () =>
|
||||
console.log(`Listening on http://localhost:${config.port}`)
|
||||
)
|
||||
150
server/index.ts
Normal file
150
server/index.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
import express from 'express'
|
||||
import cookieParser from 'cookie-parser'
|
||||
import session from 'express-session'
|
||||
import morgan from 'morgan'
|
||||
import path from 'path'
|
||||
import 'dotenv/config'
|
||||
|
||||
import root from './server'
|
||||
import { errorHandler } from './error'
|
||||
import kfuM241Router from './routers/kfu-m-24-1'
|
||||
import epja20241Router from './routers/epja-2024-1'
|
||||
import todoRouter from './routers/todo'
|
||||
import dogsittersFinderRouter from './routers/dogsitters-finder'
|
||||
import kazanExploreRouter from './routers/kazan-explore'
|
||||
import edateamRouter from './routers/edateam-legacy'
|
||||
import dryWashRouter from './routers/dry-wash'
|
||||
import freetrackerRouter from './routers/freetracker'
|
||||
import dhsTestingRouter from './routers/dhs-testing'
|
||||
import gamehubRouter from './routers/gamehub'
|
||||
import escRouter from './routers/esc'
|
||||
import connectmeRouter from './routers/connectme'
|
||||
import questioneerRouter from './routers/questioneer'
|
||||
import { setIo } from './io'
|
||||
|
||||
export const app = express()
|
||||
|
||||
// Динамический импорт rotating-file-stream
|
||||
const initServer = async () => {
|
||||
const rfs = await import('rotating-file-stream')
|
||||
const accessLogStream = rfs.createStream("access.log", {
|
||||
size: "10M",
|
||||
interval: "1d",
|
||||
compress: "gzip",
|
||||
path: path.join(__dirname, "log"),
|
||||
})
|
||||
|
||||
const errorLogStream = rfs.createStream("error.log", {
|
||||
size: "10M",
|
||||
interval: "1d",
|
||||
compress: "gzip",
|
||||
path: path.join(__dirname, "log"),
|
||||
})
|
||||
|
||||
app.use(cookieParser())
|
||||
app.use(
|
||||
morgan("combined", {
|
||||
stream: accessLogStream,
|
||||
skip: function (req, res) {
|
||||
return res.statusCode >= 400
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
// log all requests to access.log
|
||||
app.use(
|
||||
morgan("combined", {
|
||||
stream: errorLogStream,
|
||||
skip: function (req, res) {
|
||||
console.log('statusCode', res.statusCode, res.statusCode <= 400)
|
||||
return res.statusCode < 400
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
console.log('warming up 🔥')
|
||||
|
||||
const server = setIo(app)
|
||||
|
||||
const sess = {
|
||||
secret: "super-secret-key",
|
||||
resave: true,
|
||||
saveUninitialized: true,
|
||||
cookie: {},
|
||||
}
|
||||
if (app.get("env") !== "development") {
|
||||
app.set("trust proxy", 1)
|
||||
}
|
||||
app.use(session(sess))
|
||||
|
||||
app.use(
|
||||
express.json({
|
||||
limit: "50mb",
|
||||
})
|
||||
)
|
||||
app.use(
|
||||
express.urlencoded({
|
||||
limit: "50mb",
|
||||
extended: true,
|
||||
})
|
||||
)
|
||||
app.use(root)
|
||||
|
||||
/**
|
||||
* Добавляйте сюда свои routers.
|
||||
*/
|
||||
app.use("/kfu-m-24-1", kfuM241Router)
|
||||
app.use("/epja-2024-1", epja20241Router)
|
||||
app.use("/v1/todo", todoRouter)
|
||||
app.use("/dogsitters-finder", dogsittersFinderRouter)
|
||||
app.use("/kazan-explore", kazanExploreRouter)
|
||||
app.use("/edateam", edateamRouter)
|
||||
app.use("/dry-wash", dryWashRouter)
|
||||
app.use("/freetracker", freetrackerRouter)
|
||||
app.use("/dhs-testing", dhsTestingRouter)
|
||||
app.use("/gamehub", gamehubRouter)
|
||||
app.use("/esc", escRouter)
|
||||
app.use('/connectme', connectmeRouter)
|
||||
app.use('/questioneer', questioneerRouter)
|
||||
|
||||
app.use(errorHandler)
|
||||
|
||||
server.listen(process.env.PORT ?? 8044, () =>
|
||||
console.log(`🚀 Сервер запущен на http://localhost:${process.env.PORT ?? 8044}`)
|
||||
)
|
||||
|
||||
// Обработка сигналов завершения процесса
|
||||
process.on('SIGTERM', () => {
|
||||
console.log('🛑 Получен сигнал SIGTERM. Выполняется корректное завершение...')
|
||||
server.close(() => {
|
||||
console.log('✅ Сервер успешно остановлен')
|
||||
process.exit(0)
|
||||
})
|
||||
})
|
||||
|
||||
process.on('SIGINT', () => {
|
||||
console.log('🛑 Получен сигнал SIGINT. Выполняется корректное завершение...')
|
||||
server.close(() => {
|
||||
console.log('✅ Сервер успешно остановлен')
|
||||
process.exit(0)
|
||||
})
|
||||
})
|
||||
|
||||
// Обработка необработанных исключений
|
||||
process.on('uncaughtException', (err) => {
|
||||
console.error('❌ Необработанное исключение:', err)
|
||||
server.close(() => {
|
||||
process.exit(1)
|
||||
})
|
||||
})
|
||||
|
||||
// Обработка необработанных отклонений промисов
|
||||
process.on('unhandledRejection', (reason, promise) => {
|
||||
console.error('⚠️ Необработанное отклонение промиса:', reason)
|
||||
server.close(() => {
|
||||
process.exit(1)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
initServer().catch(console.error)
|
||||
13
server/io.js
13
server/io.js
@@ -1,13 +0,0 @@
|
||||
const { Server } = require('socket.io')
|
||||
const { createServer } = require('http')
|
||||
|
||||
let io = null
|
||||
|
||||
module.exports.setIo = (app) => {
|
||||
const server = createServer(app)
|
||||
io = new Server(server, {})
|
||||
|
||||
return server
|
||||
}
|
||||
|
||||
module.exports.getIo = () => io
|
||||
13
server/io.ts
Normal file
13
server/io.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { Server } from 'socket.io'
|
||||
import { createServer } from 'http'
|
||||
|
||||
let io = null
|
||||
|
||||
export const setIo = (app) => {
|
||||
const server = createServer(app)
|
||||
io = new Server(server, {})
|
||||
|
||||
return server
|
||||
}
|
||||
|
||||
export const getIo = () => io
|
||||
16
server/models/ErrorLog.ts
Normal file
16
server/models/ErrorLog.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import mongoose from 'mongoose'
|
||||
|
||||
const ErrorLogSchema = new mongoose.Schema({
|
||||
message: { type: String, required: true },
|
||||
stack: { type: String },
|
||||
path: { type: String },
|
||||
method: { type: String },
|
||||
query: { type: Object },
|
||||
body: { type: Object },
|
||||
createdAt: { type: Date, default: Date.now },
|
||||
})
|
||||
|
||||
// Индекс для быстрого поиска по дате создания
|
||||
ErrorLogSchema.index({ createdAt: 1 })
|
||||
|
||||
export const ErrorLog = mongoose.model('ErrorLog', ErrorLogSchema)
|
||||
@@ -1,7 +1,7 @@
|
||||
const mongoose = require('mongoose');
|
||||
|
||||
// Типы вопросов
|
||||
const QUESTION_TYPES = {
|
||||
export const QUESTION_TYPES = {
|
||||
SINGLE_CHOICE: 'single_choice', // Один вариант
|
||||
MULTIPLE_CHOICE: 'multiple_choice', // Несколько вариантов
|
||||
TEXT: 'text', // Текстовый ответ
|
||||
@@ -10,7 +10,7 @@ const QUESTION_TYPES = {
|
||||
};
|
||||
|
||||
// Типы отображения
|
||||
const DISPLAY_TYPES = {
|
||||
export const DISPLAY_TYPES = {
|
||||
DEFAULT: 'default',
|
||||
TAG_CLOUD: 'tag_cloud',
|
||||
VOTING: 'voting',
|
||||
@@ -51,10 +51,5 @@ const questionnaireSchema = new mongoose.Schema({
|
||||
publicLink: { type: String, required: true } // ссылка для голосования
|
||||
});
|
||||
|
||||
const Questionnaire = mongoose.model('Questionnaire', questionnaireSchema);
|
||||
export const Questionnaire = mongoose.model('Questionnaire', questionnaireSchema);
|
||||
|
||||
module.exports = {
|
||||
Questionnaire,
|
||||
QUESTION_TYPES,
|
||||
DISPLAY_TYPES
|
||||
};
|
||||
@@ -1,33 +0,0 @@
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const router = require('express').Router()
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
const pkg = require('../package.json')
|
||||
|
||||
require('./utils/mongoose')
|
||||
const folderPath = path.resolve(__dirname, './routers')
|
||||
const folders = fs.readdirSync(folderPath)
|
||||
|
||||
router.get('/', async (req, res) => {
|
||||
// throw new Error('check error message')
|
||||
res.send(`
|
||||
<h1>multy stub is working v${pkg.version}</h1>
|
||||
<ul>
|
||||
${folders.map((f) => `<li>${f}</li>`).join('')}
|
||||
</ul>
|
||||
|
||||
<h2>models</h2>
|
||||
<ul>${
|
||||
(await Promise.all(
|
||||
(await mongoose.modelNames()).map(async (name) => {
|
||||
const count = await mongoose.model(name).countDocuments()
|
||||
return `<li>${name} - ${count}</li>`
|
||||
}
|
||||
)
|
||||
)).map(t => t).join(' ')
|
||||
}</ul>
|
||||
`)
|
||||
})
|
||||
|
||||
module.exports = router
|
||||
@@ -1,15 +0,0 @@
|
||||
const router = require('express').Router();
|
||||
|
||||
router.get('/recipe-data', (request, response) => {
|
||||
response.send(require('./json/recipe-data/success.json'))
|
||||
})
|
||||
|
||||
router.get('/userpage-data', (req, res)=>{
|
||||
res.send(require('./json/userpage-data/success.json'))
|
||||
})
|
||||
|
||||
router.get('/homepage-data', (req, res)=>{
|
||||
res.send(require('./json/homepage-data/success.json'))
|
||||
})
|
||||
|
||||
module.exports = router;
|
||||
21
server/routers/edateam-legacy/index.ts
Normal file
21
server/routers/edateam-legacy/index.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { Router } from 'express';
|
||||
|
||||
import recipeData from './json/recipe-data/success.json';
|
||||
import userpageData from './json/userpage-data/success.json';
|
||||
import homepageData from './json/homepage-data/success.json';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.get('/recipe-data', (request, response) => {
|
||||
response.send(recipeData)
|
||||
})
|
||||
|
||||
router.get('/userpage-data', (req, res)=>{
|
||||
res.send(userpageData)
|
||||
})
|
||||
|
||||
router.get('/homepage-data', (req, res)=>{
|
||||
res.send(homepageData)
|
||||
})
|
||||
|
||||
export default router;
|
||||
962
server/server.ts
Normal file
962
server/server.ts
Normal file
@@ -0,0 +1,962 @@
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { Router } from 'express'
|
||||
import mongoose from 'mongoose'
|
||||
|
||||
import pkg from '../package.json'
|
||||
|
||||
import './utils/mongoose'
|
||||
import { ErrorLog } from './models/ErrorLog'
|
||||
|
||||
const folderPath = path.resolve(__dirname, './routers')
|
||||
const folders = fs.readdirSync(folderPath)
|
||||
|
||||
// Определение типов
|
||||
interface FileInfo {
|
||||
path: string;
|
||||
type: 'file';
|
||||
endpoints: number;
|
||||
}
|
||||
|
||||
interface DirectoryInfo {
|
||||
path: string;
|
||||
type: 'directory';
|
||||
endpoints: number;
|
||||
children: (FileInfo | DirectoryInfo)[];
|
||||
}
|
||||
|
||||
interface DirScanResult {
|
||||
items: (FileInfo | DirectoryInfo)[];
|
||||
totalEndpoints: number;
|
||||
}
|
||||
|
||||
// Функция для поиска эндпоинтов в файлах
|
||||
function countEndpoints(filePath) {
|
||||
if (!fs.existsSync(filePath) || !filePath.endsWith('.js') && !filePath.endsWith('.ts')) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = fs.readFileSync(filePath, 'utf8');
|
||||
const httpMethods = ['get', 'post', 'put', 'delete', 'patch'];
|
||||
|
||||
return httpMethods.reduce((count, method) => {
|
||||
const regex = new RegExp(`router\\.${method}\\(`, 'gi');
|
||||
const matches = content.match(regex) || [];
|
||||
return count + matches.length;
|
||||
}, 0);
|
||||
} catch (err) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Функция для рекурсивного обхода директорий
|
||||
function getAllDirs(dir, basePath = ''): DirScanResult {
|
||||
const items: (FileInfo | DirectoryInfo)[] = [];
|
||||
let totalEndpoints = 0;
|
||||
|
||||
try {
|
||||
const dirItems = fs.readdirSync(dir);
|
||||
|
||||
for (const item of dirItems) {
|
||||
const itemPath = path.join(dir, item);
|
||||
const relativePath = path.join(basePath, item);
|
||||
const stat = fs.statSync(itemPath);
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
const dirResult = getAllDirs(itemPath, relativePath);
|
||||
totalEndpoints += dirResult.totalEndpoints;
|
||||
|
||||
items.push({
|
||||
path: relativePath,
|
||||
type: 'directory',
|
||||
endpoints: dirResult.totalEndpoints,
|
||||
children: dirResult.items
|
||||
});
|
||||
} else {
|
||||
const fileEndpoints = countEndpoints(itemPath);
|
||||
totalEndpoints += fileEndpoints;
|
||||
|
||||
items.push({
|
||||
path: relativePath,
|
||||
type: 'file',
|
||||
endpoints: fileEndpoints
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Ошибка при чтении директории ${dir}:`, err);
|
||||
}
|
||||
|
||||
return {
|
||||
items,
|
||||
totalEndpoints
|
||||
};
|
||||
}
|
||||
|
||||
// Функция для генерации HTML-списка директорий
|
||||
function generateDirList(dirs: (FileInfo | DirectoryInfo)[], level = 0) {
|
||||
if (dirs.length === 0) return '';
|
||||
|
||||
const indent = level * 20;
|
||||
|
||||
return `<ul class="directory-list" style="padding-left: ${indent}px">${dirs.map(item => {
|
||||
if (item.type === 'directory') {
|
||||
const endpointClass = item.endpoints > 0 ? 'has-endpoints' : '';
|
||||
const endpointInfo = item.endpoints > 0
|
||||
? `<span class="endpoint-count" title="Количество эндпоинтов в директории">${item.endpoints}</span>`
|
||||
: '';
|
||||
|
||||
return `
|
||||
<li class="directory ${endpointClass}">
|
||||
<div class="dir-item" data-expandable="true">
|
||||
<span class="expand-icon">▶</span>
|
||||
<span class="dir-name">${path.basename(item.path)}</span>
|
||||
${endpointInfo}
|
||||
</div>
|
||||
<div class="subdirectory" style="display: none;">
|
||||
${generateDirList(item.children, level + 1)}
|
||||
</div>
|
||||
</li>
|
||||
`;
|
||||
} else {
|
||||
const endpointClass = item.endpoints > 0 ? 'has-endpoints' : '';
|
||||
const endpointInfo = item.endpoints > 0
|
||||
? `<span class="endpoint-count" title="Количество эндпоинтов">${item.endpoints}</span>`
|
||||
: '';
|
||||
|
||||
return `
|
||||
<li class="file ${endpointClass}">
|
||||
<div class="file-item" data-path="${item.path}">
|
||||
<span class="file-icon">📄</span>
|
||||
<span class="file-name">${path.basename(item.path)}</span>
|
||||
${endpointInfo}
|
||||
</div>
|
||||
</li>
|
||||
`;
|
||||
}
|
||||
}).join('')}</ul>`;
|
||||
}
|
||||
|
||||
const router = Router()
|
||||
|
||||
// Эндпоинт для получения содержимого файла
|
||||
router.get('/file-content', async (req, res) => {
|
||||
try {
|
||||
const filePath = req.query.path as string;
|
||||
if (!filePath) {
|
||||
return res.status(400).json({ error: 'Путь к файлу не указан' });
|
||||
}
|
||||
|
||||
// Используем корень проекта для получения абсолютного пути к файлу
|
||||
const projectRoot = path.resolve(__dirname, 'routers');
|
||||
const absolutePath = path.join(projectRoot, filePath);
|
||||
|
||||
// Проверка, что путь не выходит за пределы проекта
|
||||
if (!absolutePath.startsWith(projectRoot)) {
|
||||
return res.status(403).json({ error: 'Доступ запрещен' });
|
||||
}
|
||||
|
||||
if (!fs.existsSync(absolutePath)) {
|
||||
return res.status(404).json({ error: 'Файл не найден' });
|
||||
}
|
||||
|
||||
// Проверяем, что это файл, а не директория
|
||||
const stat = fs.statSync(absolutePath);
|
||||
if (!stat.isFile()) {
|
||||
return res.status(400).json({ error: 'Указанный путь не является файлом' });
|
||||
}
|
||||
|
||||
// Проверяем размер файла, чтобы не загружать слишком большие файлы
|
||||
const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB
|
||||
if (stat.size > MAX_FILE_SIZE) {
|
||||
return res.status(413).json({
|
||||
error: 'Файл слишком большой',
|
||||
size: stat.size,
|
||||
maxSize: MAX_FILE_SIZE
|
||||
});
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(absolutePath, 'utf8');
|
||||
const fileExtension = path.extname(absolutePath).slice(1);
|
||||
|
||||
res.json({
|
||||
content,
|
||||
extension: fileExtension,
|
||||
fileName: path.basename(absolutePath)
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Ошибка при чтении файла:', err);
|
||||
res.status(500).json({ error: 'Ошибка при чтении файла' });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/', async (req, res) => {
|
||||
// throw new Error('check error message')
|
||||
// Используем корень проекта вместо только директории routers
|
||||
const projectRoot = path.resolve(__dirname, 'routers');
|
||||
const routersPath = path.resolve(__dirname, 'routers');
|
||||
const routerFolders = fs.readdirSync(routersPath);
|
||||
|
||||
const directoryResult = getAllDirs(projectRoot);
|
||||
const totalEndpoints = directoryResult.totalEndpoints;
|
||||
|
||||
// Получаем последние 10 ошибок
|
||||
const latestErrors = await ErrorLog.find().sort({ createdAt: -1 }).limit(10);
|
||||
|
||||
// Сформируем HTML для секции с ошибками
|
||||
let errorsHtml = '';
|
||||
if (latestErrors.length > 0) {
|
||||
errorsHtml = latestErrors.map(error => `
|
||||
<div class="error-card">
|
||||
<div class="error-header">
|
||||
<h3 class="error-message">${error.message}</h3>
|
||||
<span class="error-date">${new Date(error.createdAt).toLocaleString()}</span>
|
||||
</div>
|
||||
<div class="error-details">
|
||||
${error.path ? `<div class="error-path">${error.method || 'GET'} ${error.path}</div>` : ''}
|
||||
${error.stack ? `<div class="error-stack">${error.stack}</div>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
} else {
|
||||
errorsHtml = '<p>Нет зарегистрированных ошибок</p>';
|
||||
}
|
||||
|
||||
// Создаем JavaScript для клиентской части
|
||||
const clientScript = `
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Директории
|
||||
document.querySelectorAll('.dir-item[data-expandable="true"]').forEach(item => {
|
||||
item.addEventListener('click', function(e) {
|
||||
const subdirectory = this.nextElementSibling;
|
||||
const isExpanded = this.classList.toggle('expanded');
|
||||
|
||||
if (isExpanded) {
|
||||
subdirectory.style.display = 'block';
|
||||
this.querySelector('.expand-icon').textContent = '▼';
|
||||
} else {
|
||||
subdirectory.style.display = 'none';
|
||||
this.querySelector('.expand-icon').textContent = '▶';
|
||||
}
|
||||
|
||||
e.stopPropagation();
|
||||
});
|
||||
});
|
||||
|
||||
// Модальное окно
|
||||
const modal = document.getElementById('fileModal');
|
||||
const closeBtn = document.querySelector('.close-modal');
|
||||
const fileContent = document.getElementById('fileContent');
|
||||
const fileLoader = document.getElementById('fileLoader');
|
||||
const modalFileName = document.getElementById('modalFileName');
|
||||
|
||||
// Закрытие модального окна
|
||||
closeBtn.addEventListener('click', function() {
|
||||
modal.style.display = 'none';
|
||||
});
|
||||
|
||||
window.addEventListener('click', function(event) {
|
||||
if (event.target == modal) {
|
||||
modal.style.display = 'none';
|
||||
}
|
||||
});
|
||||
|
||||
// Обработчик для файлов
|
||||
document.querySelectorAll('.file-item').forEach(item => {
|
||||
item.addEventListener('click', async function() {
|
||||
const filePath = this.getAttribute('data-path');
|
||||
if (!filePath) return;
|
||||
|
||||
// Показываем модальное окно и лоадер
|
||||
modal.style.display = 'block';
|
||||
fileContent.style.display = 'none';
|
||||
fileLoader.style.display = 'block';
|
||||
modalFileName.textContent = 'Загрузка...';
|
||||
|
||||
try {
|
||||
const response = await fetch('/file-content?path=' + encodeURIComponent(filePath));
|
||||
if (!response.ok) {
|
||||
throw new Error('Ошибка при загрузке файла');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Отображаем содержимое файла
|
||||
fileLoader.style.display = 'none';
|
||||
fileContent.style.display = 'block';
|
||||
fileContent.textContent = data.content;
|
||||
modalFileName.textContent = data.fileName;
|
||||
|
||||
// Подсветка синтаксиса
|
||||
const extensionMap = {
|
||||
'js': 'javascript',
|
||||
'ts': 'typescript',
|
||||
'json': 'json',
|
||||
'css': 'css',
|
||||
'html': 'xml',
|
||||
'xml': 'xml',
|
||||
'md': 'markdown',
|
||||
'yaml': 'yaml',
|
||||
'yml': 'yaml',
|
||||
'sh': 'bash',
|
||||
'bash': 'bash'
|
||||
};
|
||||
|
||||
const language = extensionMap[data.extension] || '';
|
||||
if (language) {
|
||||
fileContent.className = 'language-' + language;
|
||||
hljs.highlightElement(fileContent);
|
||||
}
|
||||
} catch (error) {
|
||||
fileLoader.style.display = 'none';
|
||||
fileContent.style.display = 'block';
|
||||
fileContent.textContent = 'Ошибка при загрузке файла: ' + error.message;
|
||||
modalFileName.textContent = 'Ошибка';
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Обработчик кнопки очистки ошибок
|
||||
const clearErrorsBtn = document.getElementById('clearErrorsBtn');
|
||||
const successAction = document.getElementById('successAction');
|
||||
|
||||
clearErrorsBtn.addEventListener('click', async function() {
|
||||
try {
|
||||
const response = await fetch('/clear-old-errors', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Ошибка при очистке старых ошибок');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Показываем сообщение об успехе
|
||||
successAction.textContent = 'Удалено ' + data.deletedCount + ' записей';
|
||||
successAction.style.display = 'block';
|
||||
|
||||
// Перезагружаем страницу через 2 секунды
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 2000);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Ошибка:', error);
|
||||
alert('Произошла ошибка: ' + error.message);
|
||||
}
|
||||
});
|
||||
});
|
||||
`;
|
||||
|
||||
res.send(`
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Multy Stub v${pkg.version}</title>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/atom-one-dark.min.css">
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/javascript.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/typescript.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/json.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/css.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/xml.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/markdown.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/yaml.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/bash.min.js"></script>
|
||||
<style>
|
||||
:root {
|
||||
--primary-color: #3f51b5;
|
||||
--secondary-color: #f50057;
|
||||
--bg-color: #f9f9f9;
|
||||
--card-bg: #ffffff;
|
||||
--text-color: #333333;
|
||||
--border-radius: 8px;
|
||||
--shadow: 0 4px 6px rgba(0,0,0,0.1);
|
||||
--hover-shadow: 0 6px 12px rgba(0,0,0,0.15);
|
||||
--transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Roboto', Arial, sans-serif;
|
||||
line-height: 1.6;
|
||||
background-color: var(--bg-color);
|
||||
color: var(--text-color);
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
h1, h2, h3 {
|
||||
color: var(--primary-color);
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
background-color: var(--card-bg);
|
||||
padding: 30px;
|
||||
border-radius: var(--border-radius);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 30px;
|
||||
padding-bottom: 15px;
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
|
||||
.stats-card {
|
||||
background: linear-gradient(135deg, var(--primary-color), #5c6bc0);
|
||||
color: white;
|
||||
padding: 15px;
|
||||
border-radius: var(--border-radius);
|
||||
box-shadow: var(--shadow);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-direction: column;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.stats-value {
|
||||
font-size: 28px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.stats-label {
|
||||
font-size: 14px;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.directory-list {
|
||||
list-style-type: none;
|
||||
padding-left: 20px;
|
||||
}
|
||||
|
||||
.directory, .file {
|
||||
margin: 5px 0;
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.dir-item, .file-item {
|
||||
padding: 8px 12px;
|
||||
border-radius: var(--border-radius);
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.dir-item:hover {
|
||||
background-color: rgba(63, 81, 181, 0.1);
|
||||
}
|
||||
|
||||
.file-item:hover {
|
||||
background-color: rgba(0, 0, 0, 0.03);
|
||||
}
|
||||
|
||||
.dir-name {
|
||||
font-weight: 500;
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
.file-name {
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.expand-icon {
|
||||
display: inline-block;
|
||||
margin-right: 8px;
|
||||
transition: transform 0.3s ease;
|
||||
font-size: 12px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
text-align: center;
|
||||
line-height: 16px;
|
||||
}
|
||||
|
||||
.file-icon {
|
||||
margin-right: 8px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.expanded .expand-icon {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.endpoint-count {
|
||||
margin-left: 10px;
|
||||
font-size: 0.75rem;
|
||||
color: #fff;
|
||||
background-color: var(--secondary-color);
|
||||
padding: 2px 8px;
|
||||
border-radius: 12px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.has-endpoints .dir-item {
|
||||
border-left: 3px solid var(--secondary-color);
|
||||
}
|
||||
|
||||
.has-endpoints .file-item {
|
||||
border-left: 3px solid var(--secondary-color);
|
||||
}
|
||||
|
||||
.section {
|
||||
margin-bottom: 30px;
|
||||
padding: 20px;
|
||||
background-color: var(--card-bg);
|
||||
border-radius: var(--border-radius);
|
||||
box-shadow: var(--shadow);
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.section:hover {
|
||||
box-shadow: var(--hover-shadow);
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
|
||||
gap: 20px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.tooltip {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.tooltip:hover .tooltip-text {
|
||||
visibility: visible;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Стили для модального окна с содержимым файла */
|
||||
.modal {
|
||||
display: none;
|
||||
position: fixed;
|
||||
z-index: 1000;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0,0,0,0.5);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
background-color: var(--card-bg);
|
||||
margin: 5% auto;
|
||||
padding: 20px;
|
||||
border-radius: var(--border-radius);
|
||||
box-shadow: var(--shadow);
|
||||
width: 80%;
|
||||
max-width: 1000px;
|
||||
max-height: 80vh;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding-bottom: 10px;
|
||||
margin-bottom: 15px;
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
|
||||
.modal-title {
|
||||
margin: 0;
|
||||
font-size: 1.5rem;
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
.close-modal {
|
||||
font-size: 28px;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
color: #aaa;
|
||||
transition: color 0.2s ease;
|
||||
}
|
||||
|
||||
.close-modal:hover {
|
||||
color: var(--secondary-color);
|
||||
}
|
||||
|
||||
.file-content {
|
||||
background-color: #282c34;
|
||||
border-radius: var(--border-radius);
|
||||
padding: 15px;
|
||||
overflow: auto;
|
||||
max-height: 60vh;
|
||||
}
|
||||
|
||||
.file-content pre {
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.file-content code {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.loader {
|
||||
border: 4px solid rgba(0, 0, 0, 0.1);
|
||||
border-left: 4px solid var(--primary-color);
|
||||
border-radius: 50%;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
animation: spin 1s linear infinite;
|
||||
margin: 30px auto;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* Стили для списка моделей */
|
||||
.models-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
|
||||
gap: 20px;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
.model-card {
|
||||
background-color: var(--card-bg);
|
||||
border-radius: var(--border-radius);
|
||||
box-shadow: var(--shadow);
|
||||
overflow: hidden;
|
||||
transition: var(--transition);
|
||||
border-left: 4px solid var(--primary-color);
|
||||
}
|
||||
|
||||
.model-card:hover {
|
||||
box-shadow: var(--hover-shadow);
|
||||
transform: translateY(-3px);
|
||||
}
|
||||
|
||||
.model-header {
|
||||
background-color: rgba(63, 81, 181, 0.1);
|
||||
padding: 12px 15px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: flex-start;
|
||||
align-items: flex-start;
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
|
||||
.model-name {
|
||||
margin: 0;
|
||||
color: var(--primary-color);
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
|
||||
.model-count {
|
||||
background-color: var(--secondary-color);
|
||||
color: white;
|
||||
padding: 3px 10px;
|
||||
border-radius: 12px;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.model-details {
|
||||
padding: 15px;
|
||||
}
|
||||
|
||||
.model-fields h4 {
|
||||
margin-bottom: 8px;
|
||||
font-size: 1rem;
|
||||
color: #555;
|
||||
}
|
||||
|
||||
.fields-list {
|
||||
list-style-type: none;
|
||||
padding-left: 5px;
|
||||
}
|
||||
|
||||
.fields-list li {
|
||||
margin-bottom: 5px;
|
||||
font-size: 0.9rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.field-name {
|
||||
font-weight: 500;
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
.field-type {
|
||||
color: #666;
|
||||
background-color: #f0f0f0;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
font-size: 0.8rem;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
/* Стили для раздела с ошибками */
|
||||
.error-card {
|
||||
background-color: var(--card-bg);
|
||||
border-radius: var(--border-radius);
|
||||
box-shadow: var(--shadow);
|
||||
overflow: hidden;
|
||||
transition: var(--transition);
|
||||
border-left: 4px solid #f44336;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.error-card:hover {
|
||||
box-shadow: var(--hover-shadow);
|
||||
}
|
||||
|
||||
.error-header {
|
||||
background-color: rgba(244, 67, 54, 0.1);
|
||||
padding: 12px 15px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
margin: 0;
|
||||
color: #f44336;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.error-date {
|
||||
color: #777;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.error-details {
|
||||
padding: 15px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.error-path {
|
||||
margin-bottom: 8px;
|
||||
font-family: monospace;
|
||||
background-color: #f5f5f5;
|
||||
padding: 3px 8px;
|
||||
border-radius: 4px;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.error-stack {
|
||||
background-color: #282c34;
|
||||
color: #e0e0e0;
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
font-family: monospace;
|
||||
white-space: pre-wrap;
|
||||
font-size: 0.8rem;
|
||||
max-height: 150px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.button {
|
||||
background-color: var(--primary-color);
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 10px 15px;
|
||||
border-radius: var(--border-radius);
|
||||
cursor: pointer;
|
||||
font-weight: 500;
|
||||
transition: var(--transition);
|
||||
text-align: center;
|
||||
display: inline-block;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.button:hover {
|
||||
background-color: #303f9f;
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.button-danger {
|
||||
background-color: #f44336;
|
||||
}
|
||||
|
||||
.button-danger:hover {
|
||||
background-color: #d32f2f;
|
||||
}
|
||||
|
||||
.button-success-action {
|
||||
display: none;
|
||||
background-color: #4CAF50;
|
||||
color: white;
|
||||
padding: 5px 10px;
|
||||
border-radius: 4px;
|
||||
position: fixed;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
z-index: 1000;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.2);
|
||||
animation: fadeOut 3s forwards;
|
||||
}
|
||||
|
||||
@keyframes fadeOut {
|
||||
0% { opacity: 1; }
|
||||
70% { opacity: 1; }
|
||||
100% { opacity: 0; }
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.container {
|
||||
padding: 15px;
|
||||
}
|
||||
|
||||
.grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
width: 95%;
|
||||
margin: 10% auto;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Multy Stub v${pkg.version}</h1>
|
||||
<div class="stats-card">
|
||||
<div class="stats-value">${totalEndpoints}</div>
|
||||
<div class="stats-label">Всего эндпоинтов</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>Routers:</h2>
|
||||
<div class="grid">
|
||||
${routerFolders.map((f) => `
|
||||
<div class="stats-card" style="background: linear-gradient(135deg, #26c6da, #00acc1);">
|
||||
<div class="stats-value">${f}</div>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>Структура директорий проекта:</h2>
|
||||
${generateDirList(directoryResult.items)}
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>Models:</h2>
|
||||
<div class="models-grid">
|
||||
${
|
||||
(await Promise.all(
|
||||
(await mongoose.modelNames()).map(async (name) => {
|
||||
const model = mongoose.model(name);
|
||||
const count = await model.countDocuments();
|
||||
// Получаем информацию о полях модели
|
||||
const schema = model.schema;
|
||||
const fields = Object.keys(schema.paths).filter(field => !['__v', '_id'].includes(field));
|
||||
|
||||
return `
|
||||
<div class="model-card">
|
||||
<div class="model-header">
|
||||
<h3 class="model-name">${name}</h3>
|
||||
<p class="model-count">${count} документов</p>
|
||||
</div>
|
||||
<div class="model-details">
|
||||
<div class="model-fields">
|
||||
<h4>Поля:</h4>
|
||||
<ul class="fields-list">
|
||||
${fields.map(field => {
|
||||
const fieldType = schema.paths[field].instance;
|
||||
return `<li><span class="field-name">${field}</span>: <span class="field-type">${fieldType}</span></li>`;
|
||||
}).join('')}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
)
|
||||
)).join('')
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>Последние ошибки:</h2>
|
||||
<button id="clearErrorsBtn" class="button button-danger">Очистить ошибки старше 10 дней</button>
|
||||
<div id="errorsContainer">
|
||||
${errorsHtml}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Модальное окно для отображения содержимого файла -->
|
||||
<div id="fileModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h3 class="modal-title" id="modalFileName">File Name</h3>
|
||||
<span class="close-modal">×</span>
|
||||
</div>
|
||||
<div id="fileContentContainer" class="file-content">
|
||||
<div id="fileLoader" class="loader"></div>
|
||||
<pre><code id="fileContent"></code></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="successAction" class="button-success-action">Операция выполнена успешно</div>
|
||||
|
||||
<script>${clientScript}</script>
|
||||
</body>
|
||||
</html>
|
||||
`)
|
||||
})
|
||||
|
||||
// Эндпоинт для очистки ошибок старше 10 дней
|
||||
router.post('/clear-old-errors', async (req, res) => {
|
||||
try {
|
||||
const tenDaysAgo = new Date();
|
||||
tenDaysAgo.setDate(tenDaysAgo.getDate() - 10);
|
||||
|
||||
const result = await ErrorLog.deleteMany({ createdAt: { $lt: tenDaysAgo } });
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
deletedCount: result.deletedCount || 0
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Ошибка при очистке старых ошибок:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: 'Ошибка при очистке старых ошибок'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export default router
|
||||
@@ -1,4 +1,4 @@
|
||||
exports.getAnswer = (errors, data, success = true) => {
|
||||
export const getAnswer = (errors, data, success = true) => {
|
||||
if (errors) {
|
||||
return {
|
||||
success: false,
|
||||
@@ -12,7 +12,7 @@ exports.getAnswer = (errors, data, success = true) => {
|
||||
}
|
||||
}
|
||||
|
||||
exports.getResponse = (errors, data, success = true) => {
|
||||
export const getResponse = (errors, data, success = true) => {
|
||||
if (errors.length) {
|
||||
return {
|
||||
success: false,
|
||||
@@ -1,4 +0,0 @@
|
||||
const rc = require('../../.serverrc')
|
||||
|
||||
// Connection URL
|
||||
exports.mongoUrl = `mongodb://${rc.mongoAddr}:${rc.mongoPort}`
|
||||
4
server/utils/const.ts
Normal file
4
server/utils/const.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import 'dotenv/config';
|
||||
|
||||
// Connection URL
|
||||
export const mongoUrl = process.env.MONGO_ADDR
|
||||
@@ -10,8 +10,11 @@ const mongoDBConnect = async () => {
|
||||
const MongoClient = new MDBClient(mongoUrl, {
|
||||
useUnifiedTopology: true,
|
||||
})
|
||||
return await MongoClient.connect()
|
||||
const client = await MongoClient.connect()
|
||||
console.log('Подключение к MongoDB успешно')
|
||||
return client
|
||||
} catch (error) {
|
||||
console.log('Неудачная попытка подключения к MongoDB')
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
@@ -27,6 +30,6 @@ const getDB = async (dbName) => {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
export {
|
||||
getDB,
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
const { mongoUrl } = require('./const')
|
||||
|
||||
mongoose.connect(`${mongoUrl}/mongoose`)
|
||||
11
server/utils/mongoose.ts
Normal file
11
server/utils/mongoose.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import mongoose from 'mongoose'
|
||||
|
||||
import { mongoUrl } from './const'
|
||||
|
||||
mongoose.connect(`${mongoUrl}`).then(() => {
|
||||
console.log('Подключение к MongoDB успешно')
|
||||
}).catch((err) => {
|
||||
console.log('Неудачная попытка подключения к MongoDB')
|
||||
console.error(err)
|
||||
})
|
||||
|
||||
112
tsconfig.json
Normal file
112
tsconfig.json
Normal file
@@ -0,0 +1,112 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
/* Visit https://aka.ms/tsconfig to read more about this file */
|
||||
|
||||
/* Projects */
|
||||
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
||||
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
||||
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
||||
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||
|
||||
/* Language and Environment */
|
||||
"target": "es2018", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
||||
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
||||
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||
|
||||
/* Modules */
|
||||
"module": "NodeNext", /* Specify what module code is generated. */
|
||||
"rootDir": ".", /* Specify the root folder within your source files. */
|
||||
"moduleResolution": "nodenext", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
||||
"resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
||||
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
||||
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
||||
"resolveJsonModule": true, /* Enable importing .json files. */
|
||||
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
||||
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||
|
||||
/* JavaScript Support */
|
||||
"allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
||||
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
||||
|
||||
/* Emit */
|
||||
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||
"outDir": "./dist", /* Specify an output folder for all emitted files. */
|
||||
// "removeComments": true, /* Disable emitting comments. */
|
||||
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
||||
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
||||
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
||||
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
||||
|
||||
/* Interop Constraints */
|
||||
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
||||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
||||
|
||||
/* Type Checking */
|
||||
"strict": false, /* Enable all strict type-checking options. */
|
||||
"noImplicitAny": false, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
||||
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
||||
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
||||
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
||||
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||
/* Completeness */
|
||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||
},
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"legacy/**/*.ts"
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user