diff --git a/Dockerfile b/Dockerfile index d37b6fc..577a78b 100644 --- a/Dockerfile +++ b/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"] diff --git a/d-scripts/rerun.sh b/d-scripts/rerun.sh index 03dbb37..d6ee428 100644 --- a/d-scripts/rerun.sh +++ b/d-scripts/rerun.sh @@ -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 diff --git a/docker-compose.yaml b/docker-compose.yaml index 76b4b32..0eb409d 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -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 \ No newline at end of file + - MONGO_ADDR=mongodb://${MONGO_INITDB_ROOT_USERNAME}:${MONGO_INITDB_ROOT_PASSWORD}@mongodb:27017 \ No newline at end of file diff --git a/eslint.config.mjs b/eslint.config.mjs index 21a1f6d..bcdabf1 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -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, { diff --git a/package-lock.json b/package-lock.json index e200158..8a9bf9e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index c7384b9..75e1d2d 100644 --- a/package.json +++ b/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" } } diff --git a/server/error.js b/server/error.js deleted file mode 100644 index b8db25c..0000000 --- a/server/error.js +++ /dev/null @@ -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 || 'Что-то пошло не так', - }) -} diff --git a/server/error.ts b/server/error.ts new file mode 100644 index 0000000..1919737 --- /dev/null +++ b/server/error.ts @@ -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 || 'Что-то пошло не так', + }) +} diff --git a/server/index.js b/server/index.js deleted file mode 100644 index 2a179cd..0000000 --- a/server/index.js +++ /dev/null @@ -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}`) -) diff --git a/server/index.ts b/server/index.ts new file mode 100644 index 0000000..d39f65f --- /dev/null +++ b/server/index.ts @@ -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) diff --git a/server/io.js b/server/io.js deleted file mode 100644 index 8df2c10..0000000 --- a/server/io.js +++ /dev/null @@ -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 diff --git a/server/io.ts b/server/io.ts new file mode 100644 index 0000000..71833d6 --- /dev/null +++ b/server/io.ts @@ -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 diff --git a/server/models/ErrorLog.ts b/server/models/ErrorLog.ts new file mode 100644 index 0000000..5923615 --- /dev/null +++ b/server/models/ErrorLog.ts @@ -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) \ No newline at end of file diff --git a/server/models/questionnaire.js b/server/models/questionnaire.ts similarity index 88% rename from server/models/questionnaire.js rename to server/models/questionnaire.ts index e08928e..aa39e23 100644 --- a/server/models/questionnaire.js +++ b/server/models/questionnaire.ts @@ -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 -}; \ No newline at end of file diff --git a/server/root.js b/server/root.js deleted file mode 100644 index cb3cc8a..0000000 --- a/server/root.js +++ /dev/null @@ -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(` -

multy stub is working v${pkg.version}

- - -

models

- - `) -}) - -module.exports = router diff --git a/server/routers/edateam-legacy/index.js b/server/routers/edateam-legacy/index.js deleted file mode 100644 index 0892e93..0000000 --- a/server/routers/edateam-legacy/index.js +++ /dev/null @@ -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; \ No newline at end of file diff --git a/server/routers/edateam-legacy/index.ts b/server/routers/edateam-legacy/index.ts new file mode 100644 index 0000000..1e3833b --- /dev/null +++ b/server/routers/edateam-legacy/index.ts @@ -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; diff --git a/server/server.ts b/server/server.ts new file mode 100644 index 0000000..1217ac2 --- /dev/null +++ b/server/server.ts @@ -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 ``; +} + +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 => ` +
+
+

${error.message}

+ ${new Date(error.createdAt).toLocaleString()} +
+
+ ${error.path ? `
${error.method || 'GET'} ${error.path}
` : ''} + ${error.stack ? `
${error.stack}
` : ''} +
+
+ `).join(''); + } else { + errorsHtml = '

Нет зарегистрированных ошибок

'; + } + + // Создаем 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(` + + + + Multy Stub v${pkg.version} + + + + + + + + + + + + + + + + +
+
+

Multy Stub v${pkg.version}

+
+
${totalEndpoints}
+
Всего эндпоинтов
+
+
+ +
+

Routers:

+
+ ${routerFolders.map((f) => ` +
+
${f}
+
+ `).join('')} +
+
+ +
+

Структура директорий проекта:

+ ${generateDirList(directoryResult.items)} +
+ +
+

Models:

+
+ ${ + (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 ` +
+
+

${name}

+

${count} документов

+
+
+
+

Поля:

+
    + ${fields.map(field => { + const fieldType = schema.paths[field].instance; + return `
  • ${field}: ${fieldType}
  • `; + }).join('')} +
+
+
+
+ `; + } + ) + )).join('') + } +
+
+ +
+

Последние ошибки:

+ +
+ ${errorsHtml} +
+
+
+ + + + +
Операция выполнена успешно
+ + + + + `) +}) + +// Эндпоинт для очистки ошибок старше 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 diff --git a/server/utils/common.js b/server/utils/common.ts similarity index 75% rename from server/utils/common.js rename to server/utils/common.ts index e0aee4f..42c19e7 100644 --- a/server/utils/common.js +++ b/server/utils/common.ts @@ -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, diff --git a/server/utils/const.js b/server/utils/const.js deleted file mode 100644 index bc12a52..0000000 --- a/server/utils/const.js +++ /dev/null @@ -1,4 +0,0 @@ -const rc = require('../../.serverrc') - -// Connection URL -exports.mongoUrl = `mongodb://${rc.mongoAddr}:${rc.mongoPort}` diff --git a/server/utils/const.ts b/server/utils/const.ts new file mode 100644 index 0000000..5d19080 --- /dev/null +++ b/server/utils/const.ts @@ -0,0 +1,4 @@ +import 'dotenv/config'; + +// Connection URL +export const mongoUrl = process.env.MONGO_ADDR diff --git a/server/utils/mongo.js b/server/utils/mongo.ts similarity index 70% rename from server/utils/mongo.js rename to server/utils/mongo.ts index 258067c..821b9c4 100644 --- a/server/utils/mongo.js +++ b/server/utils/mongo.ts @@ -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, } diff --git a/server/utils/mongoose.js b/server/utils/mongoose.js deleted file mode 100644 index d11d7bc..0000000 --- a/server/utils/mongoose.js +++ /dev/null @@ -1,5 +0,0 @@ -const mongoose = require('mongoose') - -const { mongoUrl } = require('./const') - -mongoose.connect(`${mongoUrl}/mongoose`) diff --git a/server/utils/mongoose.ts b/server/utils/mongoose.ts new file mode 100644 index 0000000..d018e66 --- /dev/null +++ b/server/utils/mongoose.ts @@ -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) +}) + diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..72ecfc4 --- /dev/null +++ b/tsconfig.json @@ -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 ''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" + ] +}