Compare commits

...

59 Commits

Author SHA1 Message Date
e73f7e2dc9 add auth in freetracker
Some checks failed
platform/multy-stub/pipeline/head There was a failure building this commit
2024-12-31 10:11:17 +03:00
571c43c33c add sberhubproject 2024-12-28 11:02:11 +03:00
61c847b58c Merge pull request 'kfu-m-24-1/eng-it-lean' (#56) from kfu-m-24-1/eng-it-lean into master
Reviewed-on: #56
2024-12-28 10:24:59 +03:00
Ruslan Zagitov
4d621c8bbe chore: add new dictionary 2024-12-27 23:32:54 +03:00
Ruslan Zagitov
ab8a9ebc99 feat: add '/units' endpoints; add 'put' and 'delete' requests to '/dictionaries' endpoint 2024-12-27 23:15:26 +03:00
2d1a4ba8db Merge pull request 'fixing stub paths' (#55) from kazan-explore into master
Reviewed-on: #55
2024-12-27 23:01:16 +03:00
9ed6808838 fixing stub paths 2024-12-27 22:55:08 +03:00
8bd3ccfce7 Merge pull request 'kazan-explore stubs changed, added translation' (#54) from kazan-explore into master
Reviewed-on: #54
2024-12-27 22:41:23 +03:00
9818550b29 kazan-explore stubs changed, added translation 2024-12-27 22:15:06 +03:00
aaeii
fe8a477b27 Merge branch 'master' of https://git.bro-js.ru/bro-students/multy-stub 2024-12-27 21:30:20 +03:00
aaeii
12af9b7c10 добавили окно с просмотром игр 2024-12-27 21:29:26 +03:00
1871f3f96a Merge pull request 'Добавлены стабы для двуфакторной авторизации' (#53) from dogsitters-finder into master
Reviewed-on: #53
2024-12-26 23:21:53 +03:00
05be7c4a26 Merge branch 'master' into dogsitters-finder 2024-12-26 23:21:24 +03:00
aaeii
46c8147172 fixed json gamehub 2024-12-25 02:26:03 +03:00
271f7cab7d Добавлены стабы для двуфакторной авторизации 2024-12-25 00:43:36 +03:00
aaeii
50e105b851 gamehub stubs 2024-12-24 16:34:43 +03:00
aaeii
da201720c0 gamehub stubs 2024-12-23 23:56:43 +03:00
b3fd86da33 Merge pull request 'feat: add crud for Masters' (#52) from feature/crud-arm-master into master
Reviewed-on: #52
2024-12-22 11:04:54 +03:00
276ef4033b feat: add crud for Masters 2024-12-21 21:33:07 +03:00
Primakov Alexandr Alexandrovich
a520692bc5 log dir ignore 2024-12-21 14:17:55 +03:00
Primakov Alexandr Alexandrovich
a327c9caeb ignore logs 2024-12-21 14:17:38 +03:00
Primakov Alexandr Alexandrovich
9a8fddee3b empty logs dir 2024-12-21 14:15:00 +03:00
149d668bea Merge pull request 'Обновил express до 5 версии + логгер' (#51) from update into master
Reviewed-on: #51
2024-12-21 14:09:59 +03:00
Primakov Alexandr Alexandrovich
5d08c4c1c2 update version + logger
All checks were successful
platform/multy-stub/pipeline/head This commit looks good
2024-12-21 00:05:12 +03:00
2356259823 Merge pull request 'feat: add kfu-m-24-1 stubs folder; include eng-it-lean stubs api' (#50) from kfu-m-24-1/eng-it-lean into master
Reviewed-on: #50
Reviewed-by: nekitboy1998 <nekitboy1998@gmail.com>
2024-12-20 11:28:27 +03:00
qosquo
872c921a53 feat: add kfu-m-24-1 stubs folder; include eng-it-lean stubs api 2024-12-19 19:51:07 +03:00
10b5207f9a Merge pull request 'feat: add fetch masters and add model' (#49) from feature/dry-wash-masters into master
Reviewed-on: #49
Reviewed-by: Primakov Alexandr Alexandrovich <primakovpro@gmail.com>
2024-12-15 20:02:41 +03:00
2ede62bcd8 Merge pull request 'added mock backend for sdk team' (#39) from sergepolin/multy-stub:sdk-team into master
Reviewed-on: #39
Reviewed-by: Primakov Alexandr Alexandrovich <primakovpro@gmail.com>
2024-12-15 19:59:22 +03:00
1788f90cde feat: add fetch masters and add model
All checks were successful
platform/multy-stub/pipeline/head This commit looks good
2024-12-15 17:53:45 +03:00
a37f7ea8a8 Merge pull request 'dhs-testing stubs' (#48) from dhs-testing into master
Reviewed-on: #48
2024-12-14 10:36:37 +03:00
18b63bed21 dhs-testing stubs
All checks were successful
platform/multy-stub/pipeline/head This commit looks good
2024-12-14 10:33:28 +03:00
707c3be3ec Merge pull request 'feat: freetracker dashboard-performer stubs' (#46) from feat/freetracker into master
Reviewed-on: #46
2024-12-13 22:07:47 +03:00
3d52ef9d4c feat: freetracker dashboard-performer stubs
All checks were successful
platform/multy-stub/pipeline/head This commit looks good
2024-12-13 22:05:42 +03:00
42944af2d3 Merge pull request 'feat: add dry wash json' (#44) from feature/dry-wash-arm into master
Reviewed-on: #44
2024-12-08 11:52:50 +03:00
f0f6b78cd0 feat: add dry wash json 2024-12-08 11:50:39 +03:00
WlfromB
7c35f17008 fix require server.index.js 2024-12-07 09:55:00 +03:00
WlfromB
0208e29ae3 old edateam stubs 2024-12-07 09:49:53 +03:00
Primakov Alexandr Alexandrovich
4d5cd104ad Merge branch 'master' of ssh://85.143.175.152:222/bro-students/multy-stub 2024-12-01 21:55:32 +03:00
Primakov Alexandr Alexandrovich
6702473053 up mongo version 2024-12-01 21:47:55 +03:00
52083097a2 Merge pull request 'dogsitter-finder' (#43) from dogsitter-finder into master
Reviewed-on: #43
2024-11-30 16:06:15 +03:00
f7ac265e3b Replace users.json to users/ folder
All checks were successful
platform/multy-stub/pipeline/head This commit looks good
2024-11-30 16:04:59 +03:00
d46841c21f Update paths to json files 2024-11-30 14:54:07 +03:00
c95b015094 Merge pull request 'Update stubs DogsittersFinder' (#42) from dogsitter-finder into master
Reviewed-on: #42
2024-11-30 14:40:32 +03:00
940349af29 Update stubs DogsittersFinder 2024-11-30 12:16:27 +03:00
268824c108 Added multy stub for project kazan-explore 2024-11-26 19:49:01 +03:00
Primakov Alexandr Alexandrovich
550554a7a5 docker compose by tag 2024-11-25 22:40:47 +03:00
f5a8585845 Merge pull request 'Перемещена папка dogsitters-finder в routes. Добавлен путь в index.js' (#41) from dogsitters-finder-3 into master
Reviewed-on: #41
2024-11-25 21:22:24 +03:00
1e67f25066 Перемещена папка dogsitters-finder в routes. Добавлен путь в index.js 2024-11-25 20:42:38 +03:00
359a136dbf added mock backend for sdk team 2024-10-19 01:32:36 +03:00
bbc315e270 Merge pull request 'get count by modelname' (#38) from feature/check-jenkins into master
Reviewed-on: #38
2024-10-16 11:57:57 +03:00
Primakov Alexandr Alexandrovich
fbb5d26c8f get count by modelname
All checks were successful
platform/multy-stub/pipeline/head This commit looks good
2024-10-16 11:55:42 +03:00
9d3edcf0dd Merge pull request 'check' (#37) from feature/check-jenkins into master
Reviewed-on: #37
2024-10-16 11:38:09 +03:00
Primakov Alexandr Alexandrovich
57eb548d6c verbose 2024-10-16 11:37:47 +03:00
Primakov Alexandr Alexandrovich
34d2889c1d fix 2024-10-16 11:24:59 +03:00
Primakov Alexandr Alexandrovich
afc782f50f check 2024-10-16 11:15:18 +03:00
Primakov Alexandr Alexandrovich
ff6e688206 fix 2024-10-16 11:12:16 +03:00
Primakov Alexandr Alexandrovich
4b0d9b4dbc mongoose + tests 2024-10-16 11:06:23 +03:00
2cfcd7347b Merge pull request 'fix plantsRouter' (#35) from nekitboy1998-patch-1 into master
Reviewed-on: #35
2024-10-15 14:43:38 +03:00
c1fe275532 fix plantsRouter 2024-10-15 14:43:06 +03:00
1366 changed files with 9206 additions and 3398 deletions

View File

@@ -1,45 +0,0 @@
module.exports = {
env: {
browser: true,
commonjs: true,
es2021: true,
},
extends: [
'airbnb-base',
],
parserOptions: {
ecmaVersion: 12,
},
rules: {
indent: ['error', 4],
semi: ['warn', 'never'],
'object-curly-newline': ['warn', {
ObjectExpression: 'always',
ObjectPattern: {
multiline: true,
},
ImportDeclaration: 'never',
ExportDeclaration: {
multiline: true, minProperties: 3,
},
}],
'consistent-return': [0],
'prefer-const': [0],
'no-unused-vars': [0],
'no-console': [0],
'global-require': [0],
'no-plusplus': [0],
'no-underscore-dangle': [0],
'import/no-dynamic-require': [0],
'no-shadow': ['warn'],
'no-restricted-syntax': ['warn'],
'max-len': ['warn'],
'linebreak-style': [0],
'prefer-destructuring': [0],
'imoprt-order': [0],
'no-param-reassign': [1],
'no-await-in-loop': [1],
'no-return-assign': [1],
'spaced-comment': [1],
},
}

4
.gitignore vendored
View File

@@ -1,3 +1,5 @@
node_modules/
.env
.idea
.idea
coverage/
server/log/

1
.npmrc
View File

@@ -1 +0,0 @@
package-lock=true

View File

@@ -1,5 +1,5 @@
module.exports = {
port: 8044,
port: process.env.PORT ?? 8044,
mongoAddr: process.env.MONGO_ADDR || 'localhost',
mongoPort: 27017,
}

View File

@@ -1,6 +1,6 @@
FROM node:18
FROM node:20
RUN mkdir -p /usr/src/app/server/
RUN mkdir -p /usr/src/app/server/log/
WORKDIR /usr/src/app/
COPY ./server /usr/src/app/server

16
Jenkinsfile vendored
View File

@@ -1,7 +1,7 @@
pipeline {
agent {
docker {
image 'node:18'
image 'node:20'
}
}
@@ -10,7 +10,7 @@ pipeline {
steps {
sh 'node -v'
sh 'npm -v'
sh 'npm install'
sh 'npm ci'
}
}
@@ -22,16 +22,16 @@ pipeline {
stage('test') {
steps {
sh 'npm run test:start'
sh 'npm run test'
}
}
stage('clean-all') {
stage('archiving') {
steps {
sh 'rm -rf .[!.]*'
sh 'rm -rf ./*'
sh 'ls -a'
script {
archiveArtifacts artifacts: 'coverage/*/**'
}
}
}
}
}
}

View File

@@ -3,4 +3,4 @@
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:4.4.13
docker run --rm -v ms_volume:/data/db --name ms-mongo -p 27017:27017 -d mongo:8.0.3

View File

@@ -1,19 +1,23 @@
version: "3"
volumes:
ms_volume:
ms_volume8:
ms_logs:
services:
mongoDb:
image: mongo:4.4.13
image: mongo:8.0.3
volumes:
- ms_volume:/data/db
- ms_volume8:/data/db
restart: always
# ports:
# - 27017:27017
multy-stubs:
build: .
# build: .
image: bro.js/ms/bh:$TAG
restart: always
volumes:
- ms_logs:/usr/src/app/server/log
ports:
- 8044:8044
environment:

16
eslint.config.mjs Normal file
View File

@@ -0,0 +1,16 @@
import globals from "globals";
import pluginJs from "@eslint/js";
export default [
{ ignores: ['server/routers/old/*'] },
{ files: ["**/*.js"], languageOptions: { sourceType: "commonjs" } },
{ languageOptions: { globals: globals.node } },
pluginJs.configs.recommended,
{
rules: {
semi: ['warn', 'never'],
'no-unused-vars': [0],
}
}
];

201
jest.config.js Normal file
View File

@@ -0,0 +1,201 @@
/**
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
/** @type {import('jest').Config} */
const config = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "C:\\Users\\alex\\AppData\\Local\\Temp\\jest",
// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
collectCoverageFrom: [
"<rootDir>/server/routers/**/*.js"
],
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
coveragePathIgnorePatterns: [
"\\\\node_modules\\\\",
"<rootDir>/server/routers/old"
],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "mjs",
// "cjs",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "\\\\node_modules\\\\"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "\\\\node_modules\\\\",
// "\\.pnp\\.[^\\\\]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
verbose: true,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
module.exports = config;

7434
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -4,7 +4,7 @@
"description": "",
"main": "index.js",
"scripts": {
"start": "npx nodemon ./server",
"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",
@@ -12,8 +12,7 @@
"redeploy": "npm run deploy:d:stop && npm run deploy:d:build && npm run deploy:d:up",
"eslint": "npx eslint ./server",
"eslint:fix": "npx eslint ./server --fix",
"test": "echo \"test complete\"",
"test:start": "start-server-and-test up:prod 8044 test"
"test": "jest"
},
"repository": {
"type": "git",
@@ -24,31 +23,34 @@
"license": "MIT",
"homepage": "https://bitbucket.org/online-mentor/multi-stub#readme",
"dependencies": {
"axios": "^1.7.7",
"bcrypt": "^5.1.0",
"body-parser": "^1.19.0",
"cookie-parser": "^1.4.5",
"cors": "^2.8.5",
"axios": "^1.7.9",
"bcrypt": "^5.1.1",
"body-parser": "^1.20.3",
"cookie-parser": "^1.4.7",
"cross-env": "^7.0.3",
"crypto-js": "^4.1.1",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"express-jwt": "^8.4.1",
"express-session": "^1.17.3",
"jsdom": "^22.1.0",
"jsonwebtoken": "^8.5.1",
"mongodb": "^3.6.8",
"mysql": "^2.18.1",
"crypto-js": "^4.2.0",
"dotenv": "^16.4.7",
"express": "5.0.1",
"express-jwt": "^8.5.1",
"express-session": "^1.18.1",
"jsdom": "^25.0.1",
"jsonwebtoken": "^9.0.2",
"mongodb": "^6.12.0",
"mongoose": "^8.9.2",
"morgan": "^1.10.0",
"pbkdf2-password": "^1.2.1",
"socket.io": "^4.7.1",
"start-server-and-test": "^1.13.1",
"uuid": "^9.0.0"
"rotating-file-stream": "^3.2.5",
"socket.io": "^4.8.1",
"uuid": "^11.0.3"
},
"devDependencies": {
"@types/node": "18.17.1",
"eslint": "8.46.0",
"eslint-config-airbnb-base": "15.0.0",
"eslint-plugin-import": "2.28.0",
"nodemon": "3.0.1"
"@eslint/js": "^9.17.0",
"@types/node": "22.10.2",
"eslint": "^9.17.0",
"globals": "^15.14.0",
"jest": "^29.7.0",
"mockingoose": "^2.16.2",
"nodemon": "3.1.9",
"supertest": "^7.0.0"
}
}

View File

@@ -0,0 +1,16 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`todo list app get list 1`] = `
{
"body": [
{
"_id": "670f69b5796ce7a9069da2f7",
"created": "2024-10-16T07:22:29.042Z",
"id": "670f69b5796ce7a9069da2f7",
"items": [],
"title": "qqq",
},
],
"success": true,
}
`;

View File

@@ -0,0 +1,34 @@
const { describe, it, expect } = require('@jest/globals')
const request = require('supertest')
const express = require('express')
const mockingoose = require('mockingoose')
const { ListModel } = require('../data/model/todo/list')
const todo = require('../routers/todo/routes')
const app = express()
app.use(todo)
const listExample = {
"title": "qqq",
"items": [],
"_id": "670f69b5796ce7a9069da2f7",
"created": "2024-10-16T07:22:29.042Z",
"id": "670f69b5796ce7a9069da2f7"
}
describe('todo list app', () => {
it('get list', (done) => {
mockingoose(ListModel)
.toReturn([listExample], 'find')
.toReturn(listExample, 'create')
request(app)
.get('/list')
.expect(200)
.then((response) => {
expect(response.body).toMatchSnapshot()
done()
})
})
})

2
server/data/const.js Normal file
View File

@@ -0,0 +1,2 @@
exports.TODO_LIST_MODEL_NAME = 'TODO_LIST'
exports.TODO_ITEM_MODEL_NAME = 'TODO_ITEM'

View File

@@ -0,0 +1,23 @@
const { Schema, model } = require('mongoose')
const { TODO_ITEM_MODEL_NAME } = require('../../const')
const schema = new Schema({
title: String,
done: { type: Boolean, default: false },
closed: Date,
created: {
type: Date, default: () => new Date().toISOString(),
},
})
schema.set('toJSON', {
virtuals: true,
versionKey: false,
})
schema.virtual('id').get(function () {
return this._id.toHexString()
})
exports.ItemModel = model(TODO_ITEM_MODEL_NAME, schema)

View File

@@ -0,0 +1,27 @@
const { Schema, model } = require('mongoose')
const { TODO_LIST_MODEL_NAME, TODO_ITEM_MODEL_NAME } = require('../../const')
const schema = new Schema({
title: String,
created: {
type: Date, default: () => new Date().toISOString(),
},
items: [{ type: Schema.Types.ObjectId, ref: TODO_ITEM_MODEL_NAME }],
})
schema.set('toJSON', {
virtuals: true,
versionKey: false,
})
schema.virtual('id').get(function () {
return this._id.toHexString()
})
schema.method('addItem', async function (itemObjectId) {
this.items.push(itemObjectId)
await this.save()
})
exports.ListModel = model(TODO_LIST_MODEL_NAME, schema)

View File

@@ -6,6 +6,7 @@ module.exports = (err, req, res, next) => {
success: false, error: 'Токен авторизации не найден',
})
}
res.status(400).send({
success: false, error: err.message || 'Что-то пошло не так',
})

View File

@@ -1,75 +1,97 @@
const express = require('express')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const session = require('express-session')
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()
const cors = require('cors')
require('dotenv').config()
require("dotenv").config()
exports.app = app
const config = require('../.serverrc')
const { setIo } = require('./io')
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.options('*', cors())
app.use(cors())
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: {
},
secret: "super-secret-key",
resave: true,
saveUninitialized: true,
cookie: {},
}
if (app.get('env') === 'production') {
app.set('trust proxy', 1)
sess.cookie.secure = true
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',
app.use(
bodyParser.json({
limit: "50mb",
})
)
app.use(
bodyParser.urlencoded({
limit: "50mb",
extended: true,
}))
app.use(require('./root'))
})
)
app.use(require("./root"))
/**
* Добавляйте сюда свои routers.
*/
app.use('/lobsters', require('./routers/lobsters'))
app.use('/example', require('./routers/example'))
// app.use('/coder', require('./routers/coder'))
//app.use('/stc-21-03', require('./routers/stc-21-03'))
//app.use('/stc-21', require('./routers/stc'))
//app.use('/stc-22-24', require('./routers/stc-22-24'))
// app.use('/bushou-api', require('./routers/bushou'))
app.use("/kfu-m-24-1", require("./routers/kfu-m-24-1"))
app.use("/epja-2024-1", require("./routers/epja-2024-1"))
app.use("/todo", require("./routers/todo/routes"))
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('/uryndyklar-api', require('./routers/uryndyklar'))
// app.use('/neptunium', require('./routers/neptunium'))
// app.use('/music-learn', require('./routers/music-learn'))
// app.use('/publicium', require('./routers/publicium'))
// app.use('/task-boss', require('./routers/task-boss'))
// app.use('/car-wash', require('./routers/car-wash'))
app.use('/zoom-bar', require('./routers/zoom-bar'))
app.use('/r-and-m', require('./routers/r-and-m'))
app.use('/my', require('./routers/my'))
app.use('/edateam', require('./routers/edateam'))
app.use('/webstar-project', require('./routers/webstar-project'))
app.use('/dogsitters-finder', require('./routers/dogsitters-finder'))
app.use('/dhs-testing', require('./routers/dhs-testing'))
app.use('/kazan-explore', require('./routers/kazan-explore'))
//app.use('/basket', require('./routers/basket'))
//app.use('/easy-project', require('./routers/easy-project'))
//app.use('/sugarbun', require('./routers/sugarbun'))
app.use('/epja-2023-2', require('./routers/epja-2023-2'))
require('./routers/hub-video')
app.use('/school-stage', require('./routers/school-stage'))
app.use('/epja-2024-1', require('./routers/epja-2024-1'))
app.use(require('./error'))
app.use(require("./error"))
server.listen(config.port, () => console.log(`Listening on http://localhost:${config.port}`))
server.listen(config.port, () =>
console.log(`Listening on http://localhost:${config.port}`)
)

View File

@@ -1,17 +1,32 @@
const router = require('express').Router()
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('/', (req, res) => {
res.send(`
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>
`)
})

View File

@@ -1,9 +1,40 @@
const { response } = require('express');
const router = require('express').Router();
const router = require("express").Router();
router.get("/users", (request, response) => {
response.send(require("./json/users.json"))
})
response.send(require("./json/users/users.json"));
});
router.post("/auth", (request, response) => {
const { phoneNumber, password } = request.body;
console.log(phoneNumber, password);
if (phoneNumber === "89999999999") {
response.send(require("./json/auth/dogsitter.success.json"));
} else if (phoneNumber === "89555555555") {
response.status(400).send(require("./json/auth/error.json"));
} else {
response.send(require("./json/auth/owner.success.json"));
}
});
router.post("/auth/2fa", (request, response) => {
const { code } = request.body;
if (code === "0000") {
response.send(require("./json/2fa/success.json"));
} else {
response.status(400).send(require("./json/2fa/error.json"));
}
});
router.post("/register", (request, response) => {
const { firstName, secondName, phoneNumber, password, role } = request.body;
console.log(phoneNumber, password, role);
if (phoneNumber === "89283244141" || phoneNumber === "89872855893") {
response.status(400).send(require("./json/register/error.json"));
} else if (role === "dogsitter") {
response.send(require("./json/register/dogsitter.success.json"));
} else {
response.send(require("./json/register/owner.success.json"));
}
});
module.exports = router;

View File

@@ -0,0 +1,4 @@
{
"status": "error",
"message": "Invalid code."
}

View File

@@ -0,0 +1,4 @@
{
"status": "success",
"message": "Two-factor authentication passed."
}

View File

@@ -0,0 +1,12 @@
{
"data": {
"id": 1,
"phoneNumber": 89283244141,
"firstName": "Вася",
"secondName": "Пупкин",
"role": "dogsitter",
"location": "Россия, республика Татарстан, Казань, улица Пушкина, 12",
"price": 1500,
"aboutMe": "Я люблю собак"
}
}

View File

@@ -0,0 +1,3 @@
{
"error": "Пользователь не найден"
}

View File

@@ -0,0 +1,9 @@
{
"data": {
"id": 3,
"phoneNumber": 89872855893,
"firstName": "Гадий",
"secondName": "Петрович",
"role": "owner"
}
}

View File

@@ -0,0 +1,12 @@
{
"data": {
"id": 5,
"phoneNumber": 89555555555,
"firstName": "Масяня",
"secondName": "Карлова",
"role": "dogsitter",
"location": "Россия, республика Татарстан, Казань, улица Пушкина, 12",
"price": 100,
"aboutMe": "Все на свете - собаки"
}
}

View File

@@ -0,0 +1,3 @@
{
"error": "Пользователь с таким номером телефона уже существует"
}

View File

@@ -0,0 +1,9 @@
{
"data": {
"id": 6,
"phoneNumber": 89888888888,
"firstName": "Генадий",
"secondName": "Паровозов",
"role": "owner"
}
}

View File

@@ -2,7 +2,6 @@
{
"id": 1,
"phone_number": 89283244141,
"password": "1234",
"first_name": "Вася",
"second_name": "Пупкин",
"role": "dogsitter",
@@ -13,7 +12,6 @@
{
"id": 2,
"phone_number": 89272844541,
"password": "1234",
"first_name": "Ваня",
"second_name": "Пуськин",
"role": "dogsitter",
@@ -24,7 +22,6 @@
{
"id": 3,
"phone_number": 89872855893,
"password": "12345",
"first_name": "Гадий",
"second_name": "Петрович",
"role": "owner"
@@ -32,10 +29,9 @@
{
"id": 4,
"phone_number": 89872844591,
"password": "12345",
"first_name": "Галкин",
"second_name": "Максим",
"role": ["owner", "dogsitter"],
"role": "dogsitter",
"location": "Россия, республика Татарстан, Казань, проспект Ямашева, 83",
"price": 1000000,
"about_me": "Миллион алых роз"

View File

@@ -0,0 +1,87 @@
const router = require('express').Router()
const {MasterModel} = require('./model/master')
const mongoose = require("mongoose")
router.get('/masters', async (req, res,next) => {
try {
const master = await MasterModel.find({})
res.status(200).send({success: true, body: master})
} catch (error) {
next(error)
}
})
router.delete('/masters/:id', async (req, res,next) => {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id)){
throw new Error('ID is required')
}
try {
const master = await MasterModel.findByIdAndDelete(id, {
new: true,
});
if (!master) {
throw new Error('master not found')
}
res.status(200).send({success: true, body: master})
} catch (error) {
next(error)
}
})
router.post('/masters', async (req, res,next) => {
const {name, phone} = req.body
if (!name || !phone ){
throw new Error('Enter name and phone')
}
try {
const master = await MasterModel.create({name, phone})
res.status(200).send({success: true, body: master})
} catch (error) {
next(error)
}
})
router.patch('/masters/:id', async (req, res, next) => {
const { id } = req.params;
if (!mongoose.Types.ObjectId.isValid(id)) {
throw new Error('ID is required')
}
const { name, phone } = req.body;
if (!name && !phone) {
throw new Error('Enter name and phone')
}
try {
const updateData = {};
if (name) updateData.name = name;
if (phone) updateData.phone = phone;
const master = await MasterModel.findByIdAndUpdate(
id,
updateData,
{ new: true }
);
if (!master) {
throw new Error('master not found')
}
res.status(200).send({ success: true, body: master });
} catch (error) {
next(error);
}
});
module.exports = router

View File

@@ -0,0 +1,9 @@
const router = require('express').Router()
router.get('/orders', (req, res) => {
res
.status(200)
.send(require(`./json/arm-orders/success.json`))
})
module.exports = router

View File

@@ -0,0 +1,10 @@
const router = require('express').Router()
const armMasterRouter = require('./arm-master')
const armOrdersRouter = require('./arm-orders')
router.use('/arm', armMasterRouter)
router.use('/arm', armOrdersRouter)
module.exports = router

View File

@@ -0,0 +1,35 @@
{
"success": true,
"body": [
{
"id": "masters1",
"name": "Иван Иванов",
"schedule": [ {
"id": "order1",
"startWashTime": "2024-11-24T10:30:00.000Z",
"endWashTime": "2024-11-24T16:30:00.000Z"
},
{
"id": "order2",
"startWashTime": "2024-11-24T11:30:00.000Z",
"endWashTime": "2024-11-24T17:30:00.000Z"
}],
"phone": "+7 900 123 45 67"
},
{
"id": "masters12",
"name": "Иван Иванов",
"schedule": [ {
"id": "order1",
"startWashTime": "2024-11-24T10:30:00.000Z",
"endWashTime": "2024-11-24T16:30:00.000Z"
},
{
"id": "order2",
"startWashTime": "2024-11-24T11:30:00.000Z",
"endWashTime": "2024-11-24T17:30:00.000Z"
}],
"phone": "+7 900 123 45 67"
}
]
}

View File

@@ -0,0 +1,25 @@
{
"success": true,
"body": [
{
"id": "order1",
"carNumber": "A123BC",
"startWashTime": "2024-11-24T10:30:00.000Z",
"endWashTime": "2024-11-24T16:30:00.000Z",
"orderDate": "2024-11-24T08:41:46.366Z",
"status": "progress",
"phone": "79001234563",
"location": "Казань, ул. Баумана, 1"
},
{
"id": "order2",
"carNumber": "A245BC",
"startWashTime": "2024-11-24T11:30:00.000Z",
"endWashTime": "2024-11-24T17:30:00.000Z",
"orderDate": "2024-11-24T07:40:46.366Z",
"status": "progress",
"phone": "79001234567",
"location": "Казань, ул. Баумана, 43"
}
]
}

View File

@@ -0,0 +1,20 @@
const { Schema, model } = require('mongoose')
const schema = new Schema({
name: {type: String, required: true},
phone: {type: String, required: true,unique: true,},
created: {
type: Date, default: () => new Date().toISOString(),
},
})
schema.set('toJSON', {
virtuals: true,
versionKey: false,
})
schema.virtual('id').get(function () {
return this._id.toHexString()
})
exports.MasterModel = model('dry-wash-master', schema)

View File

@@ -0,0 +1,30 @@
const { Schema, model } = require('mongoose')
const schema = new Schema({
startWashTime: {type: String, required: true},
endWashTime: {type: String, required: true},
orderDate: {type: String, required: true},
location: {type: String, required: true},
phone: {type: String, required: true},
status: {type: String, required: true},
carNumber: {type: String, required: true},
created: {
type: Date, default: () => new Date().toISOString(),
},
updated: {
type: Date, default: () => new Date().toISOString(),
},
master: {type: Schema.Types.ObjectId, ref: 'dry-wash-master'},
notes: String,
})
schema.set('toJSON', {
virtuals: true,
versionKey: false,
})
schema.virtual('id').get(function () {
return this._id.toHexString()
})
exports.OrderModel = model('dry-wash-order', schema)

View File

@@ -0,0 +1,107 @@
{
"info": {
"_postman_id": "e91fbcf7-3c7b-420d-a49e-4dbb6199c14a",
"name": "dry-wash",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
"_exporter_id": "27705820"
},
"item": [
{
"name": "arm",
"item": [
{
"name": "create master",
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": "{\n \"name\":\"Anto234\",\n \"phone\": \"89172420577\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{host}}/arm/master",
"host": [
"{{host}}"
],
"path": [
"arm",
"master"
]
}
},
"response": []
},
{
"name": "get masters",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{host}}/arm/master-list",
"host": [
"{{host}}"
],
"path": [
"arm",
"master-list"
]
}
},
"response": []
},
{
"name": "delete master",
"request": {
"method": "DELETE",
"header": [],
"url": {
"raw": "{{host}}/arm/masters/{{id}}",
"host": [
"{{host}}"
],
"path": [
"arm",
"masters",
"{{id}}"
]
}
},
"response": []
},
{
"name": "update master",
"request": {
"method": "PATCH",
"header": [],
"body": {
"mode": "raw",
"raw": "{\n \"name\":\"Anto234\",\n \"phone\": \"89172420577\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{host}}/arm/masters/{{id}}",
"host": [
"{{host}}"
],
"path": [
"arm",
"masters",
"{{id}}"
]
}
},
"response": []
}
]
}
]
}

View File

@@ -0,0 +1,15 @@
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;

View File

@@ -0,0 +1,112 @@
{
"data": [
{
"src": "pancakes_meat",
"alt": "Фотография блинчиков с мясом, сыром и луком",
"href": "?=dish01",
"name": "Блинчики с мясом, сыром и лучком",
"category": [
"Ужины"
]
},
{
"src": "cheesecakes",
"alt": "Фотография сырников из творога",
"href": "?=dish02",
"name": "Сырники из творога",
"category": [
"Завтраки"
]
},
{
"src": "borsch",
"alt": "Фотография борща",
"href": "?=dish03",
"name": "Борщ",
"category": [
"Супы"
]
},
{
"src": "vareniki",
"alt": "Фотография вареников",
"href": "?=dish04",
"name": "Ленивые вареники",
"category": [
"Ужины"
]
},
{
"src": "rice_porridge",
"alt": "Фотография рисовой каши",
"href": "?=dish05",
"name": "Рисовая каша",
"category": [
"Завтраки"
]
},
{
"src": "cutlets",
"alt": "Фотография котлет по-киевски",
"href": "?=dish06",
"name": "Котлеты по-киевски",
"category": [
"Обеды"
]
},
{
"src": "draniki",
"alt": "Фотография драников",
"href": "?=dish07",
"name": "Драники",
"category": [
"Обеды"
]
},
{
"src": "meringue",
"alt": "Фотография безе",
"href": "?=dish08",
"name": "Безе",
"category": [
"Выпечка и десерты"
]
},
{
"src": "goulash",
"alt": "Фотография гуляша",
"href": "?=dish09",
"name": "Гуляш",
"category": [
"Мясо"
]
},
{
"src": "pancakes_cherries",
"alt": "Фотография блинчиков с вишней и творожным сыром",
"href": "?=dish10",
"name": "Блинчики с вишней и творожным сыром",
"category": [
"Завтраки"
]
},
{
"src": "canned_soup",
"alt": "Фотография супа из рыбных консервов",
"href": "?=dish11",
"name": "Суп из рыбных консервов",
"category": [
"Супы"
]
},
{
"src": "salad",
"alt": "Фотография салата",
"href": "?=dish12",
"name": "Салат \"Весенний\"",
"category": [
"Салаты"
]
}
]
}

View File

@@ -1,147 +1,147 @@
const adminRouter = require('express').Router();
const fs = require('fs');
const path = require('path');
const { TOKEN } = require('../const');
require('dotenv').config();
const adminRouter = require('express').Router()
const fs = require('fs')
const path = require('path')
const { TOKEN } = require('../const')
require('dotenv').config()
const dataFilePath = path.join(__dirname, '../data.json');
let data = require('../data.json');
const dataFilePath = path.join(__dirname, '../data.json')
let data = require('../data.json')
const verifyToken = (req, res, next) => {
const token = req.headers['authorization'];
const token = req.headers['authorization']
if (token === TOKEN) {
next();
next()
} else {
res.status(403).send({ 'status': 'Failed', 'data': 'Invalid token' });
res.status(403).send({ 'status': 'Failed', 'data': 'Invalid token' })
}
};
}
const saveData = (data) => {
fs.writeFileSync(dataFilePath, JSON.stringify(data, null, 2), 'utf-8');
};
fs.writeFileSync(dataFilePath, JSON.stringify(data, null, 2), 'utf-8')
}
adminRouter.post('/edit/nickname', verifyToken, (req, res) => {
const { name, colored } = req.body;
const { name, colored } = req.body
if (!name || !colored) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Nickname is required' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Nickname is required' })
}
data.nickname = { name, colored };
saveData(data);
data.nickname = { name, colored }
saveData(data)
res.status(200).send({ 'status': 'OK', 'data': 'Nickname updated successfully' });
});
res.status(200).send({ 'status': 'OK', 'data': 'Nickname updated successfully' })
})
adminRouter.post('/edit/tech-stack', verifyToken, (req, res) => {
const { techStack } = req.body;
const { techStack } = req.body
if (!techStack || !Array.isArray(techStack)) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Valid tech stack is required' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Valid tech stack is required' })
}
data.techStack = techStack;
saveData(data);
data.techStack = techStack
saveData(data)
res.status(200).send({ 'status': 'OK', 'data': 'Tech stack updated successfully' });
});
res.status(200).send({ 'status': 'OK', 'data': 'Tech stack updated successfully' })
})
adminRouter.post('/edit/city', verifyToken, (req, res) => {
const { city } = req.body;
const { city } = req.body
if (!city) {
return res.status(400).send({ 'status': 'Failed', 'data': 'City is required' });
return res.status(400).send({ 'status': 'Failed', 'data': 'City is required' })
}
const isValid = typeof city === 'object' && 'name' in city && 'href' in city;
const isValid = typeof city === 'object' && 'name' in city && 'href' in city
if (!isValid) {
return res.status(400).send({ 'status': 'Failed', 'data': 'City must contain href and name' });
return res.status(400).send({ 'status': 'Failed', 'data': 'City must contain href and name' })
}
data.city = city;
saveData(data);
data.city = city
saveData(data)
res.status(200).send({ 'status': 'OK', 'data': 'City updated successfully' });
});
res.status(200).send({ 'status': 'OK', 'data': 'City updated successfully' })
})
adminRouter.post('/edit/github-repo', verifyToken, (req, res) => {
const { github } = req.body;
const { github } = req.body
if (!github) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Github is required' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Github is required' })
}
const isValid = typeof github === 'object' && 'author' in github && 'repo' in github;
const isValid = typeof github === 'object' && 'author' in github && 'repo' in github
if (!isValid) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Github must contain author and repo' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Github must contain author and repo' })
}
data.githubRepo = github;
saveData(data);
data.githubRepo = github
saveData(data)
res.status(200).send({ 'status': 'OK', 'data': 'Github updated successfully' });
});
res.status(200).send({ 'status': 'OK', 'data': 'Github updated successfully' })
})
adminRouter.post('/edit/nav-links', verifyToken, (req, res) => {
const { navLinks } = req.body;
const { navLinks } = req.body
if (!navLinks || !Array.isArray(navLinks)) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Valid navLinks are required' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Valid navLinks are required' })
}
const isValid = navLinks.every(link =>
link && typeof link === 'object' && 'href' in link && 'title' in link
);
)
if (!isValid) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Each navLink must contain href and title' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Each navLink must contain href and title' })
}
data.navLinks = navLinks;
saveData(data);
data.navLinks = navLinks
saveData(data)
res.status(200).send({ 'status': 'OK', 'data': 'Navigation links updated successfully' });
});
res.status(200).send({ 'status': 'OK', 'data': 'Navigation links updated successfully' })
})
adminRouter.post('/edit/links', verifyToken, (req, res) => {
const { links } = req.body;
const { links } = req.body
if (!links || !Array.isArray(links)) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Valid links are required' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Valid links are required' })
}
const isValid = links.every(link =>
link && typeof link === 'object' && 'href' in link && 'title' in link
);
)
if (!isValid) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Each link must contain href and title' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Each link must contain href and title' })
}
data.links = links;
saveData(data);
data.links = links
saveData(data)
res.status(200).send({ 'status': 'OK', 'data': 'Links updated successfully' });
});
res.status(200).send({ 'status': 'OK', 'data': 'Links updated successfully' })
})
adminRouter.post('/edit/projects', verifyToken, (req, res) => {
const { projects } = req.body;
const { projects } = req.body
if (!projects) {
return res.status(400).send({ 'status': 'Failed', 'data': 'Projects are required' });
return res.status(400).send({ 'status': 'Failed', 'data': 'Projects are required' })
}
const projectFields = ['id', 'title', 'description', 'link', 'techStack', 'image'];
const projectFields = ['id', 'title', 'description', 'link', 'techStack', 'image']
const isValidProject = (project) => {
return projectFields.every(field => field && field in project);
return projectFields.every(field => field && field in project)
}
const allProjectsValid = projects.every(project => isValidProject(project));
const allProjectsValid = projects.every(project => isValidProject(project))
if (!allProjectsValid) {
return res.status(400).send({ 'status': 'Failed', 'data': 'All projects must contain ' + projectFields.join(", ") });
return res.status(400).send({ 'status': 'Failed', 'data': 'All projects must contain ' + projectFields.join(", ") })
}
data.projects = projects;
saveData(data);
data.projects = projects
saveData(data)
res.status(200).send({ 'status': 'OK', 'data': 'Projects updated successfully' });
});
res.status(200).send({ 'status': 'OK', 'data': 'Projects updated successfully' })
})
module.exports = adminRouter;
module.exports = adminRouter

View File

@@ -1,16 +1,16 @@
const authRouter = require('express').Router();
const { TOKEN } = require('../const');
const authRouter = require('express').Router()
const { TOKEN } = require('../const')
module.exports = authRouter;
module.exports = authRouter
authRouter.post('/login', (req, res) => {
const { email, password } = req.body;
console.log(`Login with email=${email} and password=${password}`);
const { email, password } = req.body
console.log(`Login with email=${email} and password=${password}`)
if (email === 'admin@admin.admin' && password === 'admin') {
res.status(200).send({ 'status': 'OK', 'data': `${TOKEN}` });
res.status(200).send({ 'status': 'OK', 'data': `${TOKEN}` })
} else {
res.status(401).send({ 'status': 'Failed!', 'data': 'Invalid email or password' });
res.status(401).send({ 'status': 'Failed!', 'data': 'Invalid email or password' })
}
});
})

View File

@@ -1,3 +1,3 @@
const TOKEN = "ASDFGHJKLLKJHGFDSDFGHJKJHGF";
const TOKEN = "ASDFGHJKLLKJHGFDSDFGHJKJHGF"
module.exports = { TOKEN }

View File

@@ -1,11 +1,11 @@
const authRouter = require('./auth');
const adminRouter = require('./admin');
const rootRouter = require('./root');
const authRouter = require('./auth')
const adminRouter = require('./admin')
const rootRouter = require('./root')
const router = require('express').Router();
const router = require('express').Router()
module.exports = router;
module.exports = router
router.use(`/auth`, authRouter);
router.use(`/admin`, adminRouter);
router.use(`/`, rootRouter);
router.use(`/auth`, authRouter)
router.use(`/admin`, adminRouter)
router.use(`/`, rootRouter)

View File

@@ -1,44 +1,44 @@
const rootRouter = require('express').Router();
const data = require('../data.json');
const rootRouter = require('express').Router()
const data = require('../data.json')
rootRouter.get('/get/nickname', (req, res) => {
res.status(200).send({ 'status': 'OK', 'data': data.nickname });
});
res.status(200).send({ 'status': 'OK', 'data': data.nickname })
})
rootRouter.get('/get/tech-stack', (req, res) => {
res.status(200).send({ 'status': 'OK', 'data': data.techStack });
});
res.status(200).send({ 'status': 'OK', 'data': data.techStack })
})
rootRouter.get('/get/github-repo', (req, res) => {
res.status(200).send({ 'status': 'OK', 'data': data.githubRepo });
});
res.status(200).send({ 'status': 'OK', 'data': data.githubRepo })
})
rootRouter.get('/get/city', (req, res) => {
res.status(200).send({ 'status': 'OK', 'data': data.city });
});
res.status(200).send({ 'status': 'OK', 'data': data.city })
})
rootRouter.get('/get/nav-links', (req, res) => {
res.status(200).send({ 'status': 'OK', 'data': data.navLinks });
});
res.status(200).send({ 'status': 'OK', 'data': data.navLinks })
})
rootRouter.get('/get/links', (req, res) => {
res.status(200).send({ 'status': 'OK', 'data': data.links });
});
res.status(200).send({ 'status': 'OK', 'data': data.links })
})
rootRouter.get('/get/projects', (req, res) => {
res.status(200).send({ 'status': 'OK', 'data': data.projects });
});
res.status(200).send({ 'status': 'OK', 'data': data.projects })
})
rootRouter.get('/get/projects/:id', (req, res) => {
const { id } = req.params;
const project = data.projects.find(p => p.id === id);
const { id } = req.params
const project = data.projects.find(p => p.id === id)
if (project) {
res.status(200).send({ status: 'OK', data: project });
res.status(200).send({ status: 'OK', data: project })
} else {
res.status(404).send({ status: 'NOT_FOUND', message: 'Project not found' });
res.status(404).send({ status: 'NOT_FOUND', message: 'Project not found' })
}
});
})
module.exports = rootRouter;
module.exports = rootRouter

View File

@@ -1,11 +1,9 @@
const express = require('express');
const plantsRouter = require('./plants/getPlants')
const calendarRouter = require('./plants_calendar/index')
const plantsRouter = require('./plants/getPlants');
const calendarRouter = require('./plants_calendar/index');
const router = require('express').Router()
const router = require('express').Router();
module.exports = router;
module.exports = router
router.use('/plants',plantsRouter)
router.use('/plants_calendar',calendarRouter)

View File

@@ -1,6 +1,6 @@
const CONFIG = {
CLIENT_ID: 'kD2JXj1faSCYAWdT4B069wQAx89CZAkXmzTinRvH',
CLIENT_SECRET: 'bJq7Uiwua52tHiLP80N60hALNtQX2wcE4Mj6yNA9OzG2iZbgHuqyeAs6WSWX6MNJdfv0Nqzb7OHta8qPZr4zxWBLTauleaMfraln3xFEvbXLDpi1Lcrwe7DxfgsQQ1E4',
};
}
module.exports = CONFIG;
module.exports = CONFIG

View File

@@ -1,14 +1,14 @@
const express = require ('express');
const axios = require ('axios');
const plantsRouter = express.Router ();
const CONFIG = require ('./config');
const express = require ('express')
const axios = require ('axios')
const plantsRouter = express.Router ()
const CONFIG = require ('./config')
async function getAccessToken () {
const formData = new FormData ();
formData.append ('grant_type', 'client_credentials');
formData.append ('client_id', CONFIG.CLIENT_ID);
formData.append ('client_secret', CONFIG.CLIENT_SECRET);
const formData = new FormData ()
formData.append ('grant_type', 'client_credentials')
formData.append ('client_id', CONFIG.CLIENT_ID)
formData.append ('client_secret', CONFIG.CLIENT_SECRET)
try {
const response = await axios.post (
@@ -17,27 +17,27 @@ async function getAccessToken () {
{
headers: {'Content-Type': 'multipart/form-data'},
}
);
)
if (response.data && response.data.access_token) {
console.log ('Access token retrieved:', response.data.access_token);
return response.data.access_token;
console.log ('Access token retrieved:', response.data.access_token)
return response.data.access_token
} else {
console.error ('Error: access_token not found in response');
return null;
console.error ('Error: access_token not found in response')
return null
}
} catch (error) {
console.error (
'Error fetching access token:',
error.response ? error.response.data : error.message
);
return null;
)
return null
}
}
async function fetchPlantData (plantId) {
const accessToken = await getAccessToken ();
const accessToken = await getAccessToken ()
if (!accessToken) {
return null;
return null
}
try {
const response = await axios.get (
@@ -47,25 +47,25 @@ async function fetchPlantData (plantId) {
Authorization: `Bearer ${accessToken}`,
},
}
);
return response.data;
)
return response.data
} catch (error) {
console.error (
'Error fetching plant data:',
error.response ? error.response.data : error.message
);
return null;
)
return null
}
}
plantsRouter.get ('/list', async (req, res) => {
const accessToken = await getAccessToken ();
const accessToken = await getAccessToken ()
if (!accessToken) {
res.status (500).send ({message: 'Error obtaining access token'});
return;
res.status (500).send ({message: 'Error obtaining access token'})
return
}
try {
const alias = req.query.alias || 'monstera';
const alias = req.query.alias || 'monstera'
const response = await axios.get (
'https://open.plantbook.io/api/v1/plant/search',
{
@@ -76,13 +76,13 @@ plantsRouter.get ('/list', async (req, res) => {
alias: alias,
},
}
);
)
const plantsList = response.data.results;
const plantsList = response.data.results
const plants = await Promise.all (
plantsList.map (async plant => {
const plantDetails = await fetchPlantData (plant.pid);
const plantDetails = await fetchPlantData (plant.pid)
return {
id: plant.pid,
alias: plant.alias,
@@ -98,23 +98,23 @@ plantsRouter.get ('/list', async (req, res) => {
min_soil_moist: plantDetails ? plantDetails.min_soil_moist : null,
max_soil_ec: plantDetails ? plantDetails.max_soil_ec : null,
min_soil_ec: plantDetails ? plantDetails.min_soil_ec : null,
};
}
})
);
)
res.send ({results: plants});
res.send ({results: plants})
} catch (error) {
console.error (
'Error fetching plant list:',
error.response ? error.response.data : error.message
);
res.status (500).send ({message: 'Error fetching plant list'});
)
res.status (500).send ({message: 'Error fetching plant list'})
}
});
})
plantsRouter.get ('/:id', async (req, res) => {
const plantId = req.params.id;
const plantData = await fetchPlantData (plantId);
const plantId = req.params.id
const plantData = await fetchPlantData (plantId)
if (plantData) {
const detailedPlantData = {
@@ -132,12 +132,12 @@ plantsRouter.get ('/:id', async (req, res) => {
max_soil_ec: plantData.max_soil_ec,
min_soil_ec: plantData.min_soil_ec,
image_url: plantData.image_url,
};
}
res.send (detailedPlantData);
res.send (detailedPlantData)
} else {
res.status (404).send ({message: 'Plant not found'});
res.status (404).send ({message: 'Plant not found'})
}
});
})
module.exports = plantsRouter;
module.exports = plantsRouter

View File

@@ -1,4 +1,4 @@
const express = require('express');
const express = require('express')
const plantsRouter = express.Router()
@@ -15,28 +15,28 @@ const plants = [
frequency: 3,
startDate: "2024-10-05",
},
];
]
const calculateWateringDates = (startDate, frequency) => {
const dates = [];
const start = new Date(startDate);
const dates = []
const start = new Date(startDate)
for (let i = 0; i < 30; i += frequency) {
const nextWateringDate = new Date(start);
nextWateringDate.setDate(start.getDate() + i);
dates.push(nextWateringDate.toISOString().split('T')[0]);
const nextWateringDate = new Date(start)
nextWateringDate.setDate(start.getDate() + i)
dates.push(nextWateringDate.toISOString().split('T')[0])
}
return dates;
};
return dates
}
const plantsWithDates = plants.map(plant => ({
...plant,
wateringDates: calculateWateringDates(plant.startDate, plant.frequency),
}));
}))
plantsWithDates.get('/api/plants', (req, res) => {
res.json(plantsWithDates);
});
plantsRouter.get('/api/plants', (req, res) => {
res.json(plantsWithDates)
})
module.exports = plantsRouter;
module.exports = plantsRouter

View File

@@ -1,43 +1,43 @@
const authRouter = require('express').Router();
const authRouter = require('express').Router()
// For creating tokens
const jwt = require('jsonwebtoken');
const jwt = require('jsonwebtoken')
const { TOKEN_KEY } = require('../key')
module.exports = authRouter;
module.exports = authRouter
const { addUserToDB, getUserFromDB } = require('../db');
const { addUserToDB, getUserFromDB } = require('../db')
// Get a user by its id
authRouter.get('/:id', (req, res) => {
const user = getUserFromDB(req.params.id);
const user = getUserFromDB(req.params.id)
if (user) {
res.status(200).send({user});
res.status(200).send({user})
} else {
res.status(404).send({message: 'User was not found'});
res.status(404).send({message: 'User was not found'})
}
})
// For login (authorization)
authRouter.post('/login', (req, res) => {
const { name, password } = req.body;
const { name, password } = req.body
const user = getUserFromDB(name);
const user = getUserFromDB(name)
// Invalid identification
if (!user) {
res.status(401).send({message: 'Invalid credentials (id)'});
return;
res.status(401).send({message: 'Invalid credentials (id)'})
return
}
// Invalid authentication
if (!password || password !== user.password) {
res.status(401).send({message: 'Invalid credentials (password)'});
return;
res.status(401).send({message: 'Invalid credentials (password)'})
return
}
// Now, authorization
@@ -45,29 +45,29 @@ authRouter.post('/login', (req, res) => {
expiresIn: '1h'
})
res.status(200).send({token});
res.status(200).send({token})
})
authRouter.post('/reg', (req, res) => {
const { name, password, nickname } = req.body;
const { name, password, nickname } = req.body
const user = getUserFromDB(name);
const user = getUserFromDB(name)
// Invalid identification
if (user) {
res.status(409).send({message: 'Such id already exists'});
return;
res.status(409).send({message: 'Such id already exists'})
return
}
if (!name || !password || !nickname) {
res.status(401).send({message: 'Empty or invalid fields'});
return;
res.status(401).send({message: 'Empty or invalid fields'})
return
}
// Add to 'DB'
const newUser = {id: name, password: password, nickname: nickname};
const newUser = {id: name, password: password, nickname: nickname}
addUserToDB(newUser)
res.status(200).send({user: newUser});
res.status(200).send({user: newUser})
})

View File

@@ -1,45 +1,45 @@
const changeRouter = require('express').Router();
const changeRouter = require('express').Router()
module.exports = changeRouter;
module.exports = changeRouter
const { getUserFromDB, deleteUserFromDB, addUserToDB } = require('../db');
const { getUserFromDB, deleteUserFromDB, addUserToDB } = require('../db')
changeRouter.post('/nickname', (req, res) => {
const { id, newNickname } = req.body;
const { id, newNickname } = req.body
const user = getUserFromDB(id);
const user = getUserFromDB(id)
// Invalid identification
if (!user) {
res.status(401).send({message: 'Invalid credentials (id)'});
return;
res.status(401).send({message: 'Invalid credentials (id)'})
return
}
const updatedUser = {
"nickname": newNickname,
"password": user.password,
"id": user.id
};
}
// Delete the old one
deleteUserFromDB(id)
// Insert updated
addUserToDB(updatedUser);
addUserToDB(updatedUser)
res.status(200).send({});
});
res.status(200).send({})
})
changeRouter.post('/password', (req, res) => {
const { id, newPassword } = req.body;
const { id, newPassword } = req.body
const user = getUserFromDB(id);
const user = getUserFromDB(id)
// Invalid identification
if (!user) {
res.status(401).send({message: 'Invalid credentials (id)'});
return;
res.status(401).send({message: 'Invalid credentials (id)'})
return
}
// Delete the old one
@@ -50,15 +50,15 @@ changeRouter.post('/password', (req, res) => {
"nickname": user.nickname,
"password": newPassword,
"id": user.id
};
addUserToDB(updatedUser);
}
addUserToDB(updatedUser)
res.status(200).send({});
});
res.status(200).send({})
})
changeRouter.delete('/:id', (req, res) => {
const { id } = req.params;
const { id } = req.params
deleteUserFromDB(id);
});
deleteUserFromDB(id)
})

View File

@@ -1,43 +1,43 @@
const chatRouter = require('express').Router();
const chatRouter = require('express').Router()
module.exports = chatRouter;
module.exports = chatRouter
const { getChatFromDB, getUsersChats, addChatToDB, getUserFromDB,
addMessageToChat} = require('../db');
addMessageToChat} = require('../db')
chatRouter.get('/item/:id1/:id2', (req, res) => {
const { id1, id2 } = req.params;
const { id1, id2 } = req.params
if (id1 === id2) {
res.status(400).send({message: 'Ids should be different'});
return;
res.status(400).send({message: 'Ids should be different'})
return
}
const chat = getChatFromDB(id1, id2);
const chat = getChatFromDB(id1, id2)
if (chat) {
res.status(200).send({chat});
res.status(200).send({chat})
} else {
res.status(404).send({message: 'Chat was not found'});
res.status(404).send({message: 'Chat was not found'})
}
})
chatRouter.post('/item/:id1/:id2', (req, res) => {
const { id1, id2 } = req.params;
const { id1, id2 } = req.params
if (id1 === id2) {
res.status(400).send({message: 'Ids should be different'});
return;
res.status(400).send({message: 'Ids should be different'})
return
}
const chat = getChatFromDB(id1, id2);
const chat = getChatFromDB(id1, id2)
if (chat) {
// Chat already exists
res.status(200).send({chat});
res.status(200).send({chat})
} else {
if (!getUserFromDB(id1) || !getUserFromDB(id2)) {
res.status(404).send({message: 'Such interlocutor does not exist'});
res.status(404).send({message: 'Such interlocutor does not exist'})
} else {
// Creating new chat
const newChat = {
@@ -46,41 +46,41 @@ chatRouter.post('/item/:id1/:id2', (req, res) => {
messages: []
}
addChatToDB(newChat);
addChatToDB(newChat)
res.status(200).send({newChat});
res.status(200).send({newChat})
}
}
})
chatRouter.get('/list/:id', (req, res) => {
const { id } = req.params;
const { id } = req.params
const userChats = getUsersChats(id);
const userChats = getUsersChats(id)
if (!userChats) {
res.status(404).send({message: 'Error with retrieving chats'});
res.status(404).send({message: 'Error with retrieving chats'})
} else {
res.status(200).send({chats: userChats});
res.status(200).send({chats: userChats})
}
})
chatRouter.post('/message/:sender/:receiver', (req, res) => {
const { sender, receiver } = req.params;
const { message } = req.body;
const { sender, receiver } = req.params
const { message } = req.body
const chat = getChatFromDB(sender, receiver);
const chat = getChatFromDB(sender, receiver)
if (!chat) {
// Chat already exists
res.status(400).send({message: "Such chat does not exist"});
res.status(400).send({message: "Such chat does not exist"})
} else {
if (!getUserFromDB(sender) || !getUserFromDB(receiver)) {
res.status(404).send({message: 'Such people do not exist'});
res.status(404).send({message: 'Such people do not exist'})
} else {
// Add new message
addMessageToChat(chat, message);
res.status(200).send({});
addMessageToChat(chat, message)
res.status(200).send({})
}
}
})

View File

@@ -1,72 +1,72 @@
// Read already defined users (pseudo-DB)
const users = require('./auth/users.json');
const chats = require('./chat/chats.json');
const users = require('./auth/users.json')
const chats = require('./chat/chats.json')
const getUserFromDB = (userID) => {
if (!userID) {return false;}
if (!userID) {return false}
// Accessing 'DB'
const user = users.find((user) => user.id === userID);
const user = users.find((user) => user.id === userID)
if (user) {
return user;
return user
} else {
return false;
return false
}
}
const deleteUserFromDB = (userID) => {
const index = users.findIndex(item => item.id === userID);
const index = users.findIndex(item => item.id === userID)
if (index !== -1) {
users.splice(index, 1);
users.splice(index, 1)
}
}
const addUserToDB = (user) => {
users.push(user);
users.push(user)
}
const getChatFromDB = (firstID, secondID) => {
if (!firstID || !secondID) {return false;}
if (!firstID || !secondID) {return false}
// Accessing 'DB'
const chat = chats.find((item) =>
(item.id1 === firstID && item.id2 === secondID) || (item.id1 === secondID && item.id2 === firstID));
(item.id1 === firstID && item.id2 === secondID) || (item.id1 === secondID && item.id2 === firstID))
if (chat) {
return chat;
return chat
} else {
return false;
return false
}
}
const getUsersChats = (userID) => {
if (!userID) {return false;}
if (!userID) {return false}
const userChats = chats.filter((chat) => (chat.id1 === userID || chat.id2 === userID));
const userChats = chats.filter((chat) => (chat.id1 === userID || chat.id2 === userID))
if (userChats) {
return userChats;
return userChats
} else {
return false;
return false
}
}
const addMessageToChat = (chat, msg) => {
chat.messages.push(msg);
chat.messages.push(msg)
}
const deleteChatFromDB = (firstID, secondID) => {
const index = chats.findIndex(item =>
(item.id1 === firstID && item.id2 === secondID) || (item.id1 === secondID && item.id2 === firstID));
(item.id1 === firstID && item.id2 === secondID) || (item.id1 === secondID && item.id2 === firstID))
if (index !== -1) {
chats.splice(index, 1);
chats.splice(index, 1)
}
}
const addChatToDB = (chat) => {
chats.push(chat);
chats.push(chat)
}

View File

@@ -1,17 +1,17 @@
const changeRouter = require("./change");
const authRouter = require("./auth");
const chatRouter = require("./chat");
const changeRouter = require("./change")
const authRouter = require("./auth")
const chatRouter = require("./chat")
const router = require('express').Router();
const router = require('express').Router()
const delay = require('./middlewares/delay');
const verify = require('./middlewares/verify');
const delay = require('./middlewares/delay')
const verify = require('./middlewares/verify')
module.exports = router;
module.exports = router
// router.use(delay(300));
// router.use('/books', delay, booksRouter);
router.use('/auth', authRouter);
router.use('/change', verify, changeRouter);
router.use('/auth', authRouter)
router.use('/change', verify, changeRouter)
router.use('/chat', verify, chatRouter)

View File

@@ -1,3 +1,3 @@
const TOKEN_KEY = '5frv12e4few3r';
const TOKEN_KEY = '5frv12e4few3r'
module.exports = { TOKEN_KEY }

View File

@@ -1,22 +1,22 @@
const jwt = require('jsonwebtoken');
const jwt = require('jsonwebtoken')
const { TOKEN_KEY } = require('../key')
function verifyToken(req, res, next) {
const token = req.headers['authorization']?.split(' ')[1];
const token = req.headers['authorization']?.split(' ')[1]
if (!token) {
return res.status(401).send({ message: 'No token provided' });
return res.status(401).send({ message: 'No token provided' })
}
// Verify token
jwt.verify(token, TOKEN_KEY, (err, decoded) => {
if (err) {
return res.status(401).send({ message: 'Unauthorized' });
return res.status(401).send({ message: 'Unauthorized' })
}
next(); // Proceed to the next middleware or route
});
next() // Proceed to the next middleware or route
})
}
module.exports = verifyToken;
module.exports = verifyToken

View File

@@ -1,5 +1,5 @@
const express = require('express')
const router = express.Router()
const { Router } = require('express')
const router = Router()
router.use('/enterfront', require('./enterfront/index'))
@@ -7,4 +7,6 @@ router.use('/cats', require('./cats/index'))
router.use('/ecliptica', require('./ecliptica/index'))
router.use('/sdk', require('./sdk/index'))
module.exports = router

View File

@@ -0,0 +1,123 @@
const router = require('express').Router();
const { v4: uuidv4 } = require('uuid');
const workout1 = {
id: uuidv4(),
title: "Toned upper body",
exercises: [
{ title: "Push ups", repsOrDuration: 12, isTimeBased: false },
{ title: "Plank", repsOrDuration: 4, isTimeBased: true },
{ title: "Bicep curl", repsOrDuration: 12, isTimeBased: false, weight: 5 },
{ title: "Bicep curl", repsOrDuration: 12, isTimeBased: false, weight: 5 },
{ title: "Bicep curl", repsOrDuration: 12, isTimeBased: false, weight: 5 },
{ title: "Bicep curl", repsOrDuration: 12, isTimeBased: false, weight: 5 },
],
tags: ['Weights', 'Arms', 'Abs', 'Chest', 'Back']
};
const workout2 = {
id: uuidv4(),
title: "Tom Platz's legs",
exercises: [
{ title: "Squats", repsOrDuration: 12, isTimeBased: false, weight: 40 },
{ title: "Leg Press", repsOrDuration: 4, isTimeBased: false, weight: 65 },
{ title: "Lunges", repsOrDuration: 2, isTimeBased: true }
],
tags: ['Weights', 'Legs']
};
const workout3 = {
id: uuidv4(),
title: "HIIT",
exercises: [
{ title: "Jumping rope", repsOrDuration: 100, isTimeBased: false },
{ title: "Burpees", repsOrDuration: 3, isTimeBased: true },
{ title: "Jumping Jacks", repsOrDuration: 50, isTimeBased: false }
],
tags: ['Cardio']
}
const savedWorkouts = [workout1, workout3];
const trainingWorkouts = [workout2];
router.post('/workout', (req, res) => {
const newWorkout = { ...req.body, id: uuidv4() };
savedWorkouts.push(newWorkout);
res.status(201).json(newWorkout);
});
router.get('/workouts', (req, res) => {
res.json(savedWorkouts);
});
router.post('/training/workout', (req, res) => {
const newWorkout = { ...req.body, id: uuidv4() };
trainingWorkouts.push(newWorkout);
res.status(201).json(newWorkout);
});
const trainings = [{ id: uuidv4(), calories: 450, date: new Date("Thu Oct 03 2024 10:05:24 GMT+0300 (Moscow Standard Time)"), emoji: "fuzzy", hours: 1, minutes: 30, isWorkoutSaved: true, workout: workout1.id }];
const days = [
new Date("Thu Oct 03 2024 10:05:24 GMT+0300 (Moscow Standard Time)"),
];
router.post('/training', (req, res) => {
const newTraining = { ...req.body, id: uuidv4() };
trainings.push(newTraining);
days.push(newTraining.date);
res.status(201).json(newTraining);
});
router.get('/training', (req, res) => {
const { date } = req.query;
if (!date) {
return res.status(400).json({ message: 'Date query parameter is required' });
}
const formattedDate = new Date(date);
const result = trainings.find(t => new Date(t.date).toDateString() === formattedDate.toDateString());
if (result) {
res.json(result);
} else {
res.status(404).json({ message: 'Training not found for the specified date' });
}
});
router.get('/training/workout', (req, res) => {
const { id } = req.query;
if (!id) {
return res.status(400).json({ message: 'Id query parameter is required' });
}
const result = trainingWorkouts.find(w => w.id === id);
if (result) {
res.json(result);
} else {
res.status(404).json({ message: 'Training with such workout not found' });
}
});
router.get('/workout', (req, res) => {
const { id } = req.query;
if (!id) {
return res.status(400).json({ message: 'Id query parameter is required' });
}
const result = savedWorkouts.find(w => w.id === id);
if (result) {
res.json(result);
} else {
res.status(404).json({ message: 'Workout not found' });
}
});
router.get('/trainings', (req, res) => {
res.json(trainings);
});
router.get('/days', (req, res) => {
res.json(days);
})
module.exports = router;

View File

@@ -1,19 +0,0 @@
const router = require('express').Router()
const first = router.get('/first', (req, res) => {
res.send({
success: true,
warnings: [{
title: 'Внимание',
text: 'Данный api создан для примера!',
}],
})
/**
* Этот эндпоинт будет доступен по адресу http://89.223.91.151:8080/multystub/example/first
*/
})
router.use('/example-api', first)
module.exports = router

View File

@@ -0,0 +1,24 @@
const Router = require('express').Router
const router = Router()
router.post('/auth/login', (req, res) => {
if (req.body.email === 'qwerty@mail.ru') {
res.status(200).send(require('./json/login/login-success.json'))
} else {
res.status(401).send(require('./json/login/login-error.json'));
}
})
router.post('/auth/register', (req, res) => {
res.status(400).send(require('./json/registration/registration-error.json'))
// res.status(201).send(require('./json/registration/registration-error.json'))
})
router.post('/auth/reset-password', (req, res) => {
res.status(200).send(require('./json/reset-password/reset-password-success.json'))
// res.status(404).send(require('./json/reset-password/reset-password-error.json'))
})
module.exports = router;

View File

@@ -0,0 +1,11 @@
{
"success": false,
"body": null,
"errors": [
{
"code": "AUTH_INVALID_CREDENTIALS",
"message": "Неверное имя пользователя или пароль"
}
],
"warnings": []
}

View File

@@ -0,0 +1,8 @@
{
"success": true,
"body": {
"token": "AUTH_TOKEN"
},
"errors": [],
"warnings": []
}

View File

@@ -0,0 +1,11 @@
{
"success": false,
"body": null,
"errors": [
{
"code": "REGISTRATION_EMAIL_TAKEN",
"message": "Электронная почта уже используется"
}
],
"warnings": []
}

View File

@@ -0,0 +1,9 @@
{
"success": true,
"body": {
"userId": "12345",
"token": "AUTH_TOKEN"
},
"errors": [],
"warnings": []
}

View File

@@ -0,0 +1,11 @@
{
"success": false,
"body": null,
"errors": [
{
"code": "RESET_PASSWORD_EMAIL_NOT_FOUND",
"message": "Адрес электронной почты не зарегистрирован"
}
],
"warnings": []
}

View File

@@ -0,0 +1,8 @@
{
"success": true,
"body": {
"message": "Отправлено электронное письмо для сброса пароля"
},
"errors": [],
"warnings": []
}

View File

@@ -0,0 +1,23 @@
const Router = require('express').Router;
const router = Router()
const timer = (_req, _res, next) => {
setTimeout(() => next(), 500)
}
router.use(timer)
router.get(
'/active',
(req, res) =>
res.send(require(`./json/active-order-success.json`))
)
router.get(
'/history',
(req, res) =>
res.send(require(`./json/history-success.json`))
)
module.exports = router

View File

@@ -0,0 +1,6 @@
{
"success": false,
"errors": [
"Не получилось получить заказ с id = 123123"
]
}

View File

@@ -0,0 +1,46 @@
{
"success": true,
"body": {
"id": "1212",
"createdAt": "2024-11-29 13:24:08",
"updatedAt": "2024-11-29 13:24:10",
"status": "in_progress",
"timeline": [
{
"color": "gray",
"children": "Москва"
},
{
"children": "Владимир, 25.10.2024 18:02"
},
{
"children": "Нижний новгород, 25.10.2024 12:21"
},
{
"children": "Казань, 25.10.2024 03:00"
}
],
"statistics": [
{
"key": "address-from",
"value": "г. Казань, ул Ильи Давыдова, стр. 87а"
},
{
"key": "address-to",
"value": "г. Москва, ул. Тверская, д. 12"
},
{
"key": "delivery",
"value": "26.10.2024 23:08"
},
{
"key": "cost",
"value": "100500₽"
},
{
"key": "customer",
"value": "ООО \"Сидоров\""
}
]
}
}

View File

@@ -0,0 +1,9 @@
{
"success": false,
"body": {
"history": []
},
"errors": [
"Что-то пошло не так"
]
}

View File

@@ -0,0 +1,187 @@
{
"success": true,
"body": {
"history": [
{
"key": 1,
"number": "12324",
"cost": 15000,
"dateEnd": 1685998800000,
"customer": "ООО \"Иванов\"",
"cityFrom": "Псков",
"cityTo": "Мурманск"
},
{
"key": 2,
"number": "12323",
"cost": 10000,
"dateEnd": 1686085200000,
"customer": "ООО \"Попов\"",
"cityFrom": "Астрахань",
"cityTo": "Ставрополь"
},
{
"key": 3,
"number": "12325",
"cost": 12000,
"dateEnd": 1686171600000,
"customer": "ООО \"Сидоров\"",
"cityFrom": "Москва",
"cityTo": "Казань"
},
{
"key": 4,
"number": "12326",
"cost": 9000,
"dateEnd": 1686258000000,
"customer": "ООО \"Петров\"",
"cityFrom": "Новосибирск",
"cityTo": "Томск"
},
{
"key": 5,
"number": "12327",
"cost": 13000,
"dateEnd": 1686344400000,
"customer": "ООО \"Смирнов\"",
"cityFrom": "Омск",
"cityTo": "Тюмень"
},
{
"key": 6,
"number": "12328",
"cost": 14000,
"dateEnd": 1686430800000,
"customer": "ООО \"Кузнецов\"",
"cityFrom": "Саратов",
"cityTo": "Самара"
},
{
"key": 7,
"number": "12329",
"cost": 11000,
"dateEnd": 1686517200000,
"customer": "ООО \"Васильев\"",
"cityFrom": "Краснодар",
"cityTo": "Сочи"
},
{
"key": 8,
"number": "12330",
"cost": 8000,
"dateEnd": 1686603600000,
"customer": "ООО \"Зайцев\"",
"cityFrom": "Пермь",
"cityTo": "Екатеринбург"
},
{
"key": 9,
"number": "12331",
"cost": 7000,
"dateEnd": 1686690000000,
"customer": "ООО \"Морозов\"",
"cityFrom": "Челябинск",
"cityTo": "Уфа"
},
{
"key": 10,
"number": "12332",
"cost": 16000,
"dateEnd": 1686776400000,
"customer": "ООО \"Павлов\"",
"cityFrom": "Волгоград",
"cityTo": "Ростов-на-Дону"
},
{
"key": 11,
"number": "12333",
"cost": 9000,
"dateEnd": 1686862800000,
"customer": "ООО \"Фролов\"",
"cityFrom": "Калининград",
"cityTo": "Смоленск"
},
{
"key": 12,
"number": "12334",
"cost": 15500,
"dateEnd": 1686949200000,
"customer": "ООО \"Богданов\"",
"cityFrom": "Нижний Новгород",
"cityTo": "Киров"
},
{
"key": 13,
"number": "12335",
"cost": 13500,
"dateEnd": 1687035600000,
"customer": "ООО \"Григорьев\"",
"cityFrom": "Тверь",
"cityTo": "Ярославль"
},
{
"key": 14,
"number": "12336",
"cost": 12500,
"dateEnd": 1687122000000,
"customer": "ООО \"Дмитриев\"",
"cityFrom": "Сургут",
"cityTo": "Ханты-Мансийск"
},
{
"key": 15,
"number": "12337",
"cost": 14500,
"dateEnd": 1687208400000,
"customer": "ООО \"Михайлов\"",
"cityFrom": "Иркутск",
"cityTo": "Братск"
},
{
"key": 16,
"number": "12338",
"cost": 10500,
"dateEnd": 1687294800000,
"customer": "ООО \"Романов\"",
"cityFrom": "Владивосток",
"cityTo": "Хабаровск"
},
{
"key": 17,
"number": "12339",
"cost": 9500,
"dateEnd": 1687381200000,
"customer": "ООО \"Федоров\"",
"cityFrom": "Якутск",
"cityTo": "Магадан"
},
{
"key": 18,
"number": "12340",
"cost": 8500,
"dateEnd": 1687467600000,
"customer": "ООО \"Жуков\"",
"cityFrom": "Симферополь",
"cityTo": "Севастополь"
},
{
"key": 19,
"number": "12341",
"cost": 11500,
"dateEnd": 1687554000000,
"customer": "ООО \"Николаев\"",
"cityFrom": "Барнаул",
"cityTo": "Бийск"
},
{
"key": 20,
"number": "12342",
"cost": 10000,
"dateEnd": 1687640400000,
"customer": "ООО \"Орлов\"",
"cityFrom": "Кемерово",
"cityTo": "Новокузнецк"
}
]
}
}

View File

@@ -0,0 +1,6 @@
const router = require('express').Router();
router.use('/performer', require('./dashboard-performer'))
router.use('/auth', require('./auth'))
module.exports = router;

View File

@@ -0,0 +1,23 @@
const router = require("express").Router();
router.get("/game-page", (request, response) => {
response.send(require("./json/gamepage/success.json"));
});
router.get("/categories", (request, response) => {
response.send(require("./json/categories/success.json"));
});
router.get("/shopping-cart", (request, response) => {
response.send(require("./json/shopping-cart/success.json"));
});
router.get("/home", (request, response) => {
response.send(require("./json/home-page-data/success.json"));
});
router.get("/all-games", (request, response) => {
response.send(require("./json/home-page-data/all-games.json"));
});
module.exports = router;

View File

@@ -0,0 +1,150 @@
{
"success": true,
"data": {
"games1": [
{
"id": 1,
"title": "How to Survive",
"price": 259,
"old_price": 500,
"image": "sales_game1",
"os": "windows"
},
{
"id": 2,
"title": "Red Solstice 2 Survivors",
"price": 561,
"image": "sales_game2",
"os": "windows"
},
{
"id": 3,
"title": "Sons Of The Forests",
"price": 820,
"old_price": 1100,
"image": "new_game2",
"os": "windows"
},
{
"id": 4,
"title": "The Witcher 3: Wild Hunt",
"price": 990,
"old_price": 1200,
"image": "leaders_game4",
"os": "windows"
},
{
"id": 5,
"title": "Atomic Heart",
"price": 1200,
"old_price": 2500,
"image": "leaders_game5",
"os": "windows"
},
{
"id": 6,
"title": "Crab Game",
"price": 600,
"old_price": 890,
"image": "leaders_game6",
"os": "windows"
}
],
"games2": [
{
"id": 1,
"title": "Alpha League",
"price": 299,
"image": "new_game1",
"os": "windows"
},
{
"id": 2,
"title": "Sons Of The Forests",
"price": 820,
"old_price": 1100,
"image": "new_game2",
"os": "windows"
},
{
"id": 3,
"title": "Pacific Drives",
"price": 1799,
"image": "new_game3",
"os": "windows"
},
{
"id": 4,
"title": "The Witcher 3: Wild Hunt",
"price": 990,
"old_price": 1200,
"image": "leaders_game4",
"os": "windows"
},
{
"id": 5,
"title": "Atomic Heart",
"price": 1200,
"old_price": 2500,
"image": "leaders_game5",
"os": "windows"
},
{
"id": 6,
"title": "Crab Game",
"price": 600,
"old_price": 890,
"image": "leaders_game6",
"os": "windows"
}
],
"games3": [
{
"id": 1,
"title": "Elden Ring",
"price": 3295,
"old_price": 3599,
"image": "leaders_game2",
"os": "windows"
},
{
"id": 2,
"title": "Counter-Strike 2",
"price": 479,
"image": "leaders_game1",
"os": "windows"
},
{
"id": 3,
"title": "PUBG: BATTLEGROUNDS",
"price": 199,
"image": "leaders_game3",
"os": "windows"
},
{
"id": 4,
"title": "The Witcher 3: Wild Hunt",
"price": 990,
"old_price": 1200,
"image": "leaders_game4",
"os": "windows"
},
{
"id": 5,
"title": "Atomic Heart",
"price": 1200,
"old_price": 2500,
"image": "leaders_game5",
"os": "windows"
},
{
"id": 6,
"title": "Crab Game",
"price": 600,
"old_price": 890,
"image": "leaders_game6",
"os": "windows"
}
]
}
}

View File

@@ -0,0 +1,24 @@
{
"success": true,
"data": {
"comments": [
{
"username": ользователь1",
"text": "Текст комментария 1"
},
{
"username": ользователь2",
"text": "Текст комментария 2"
},
{
"username": ользователь3",
"text": "Текст комментария 3"
},
{
"username": ользователь4",
"text": "Текст комментария 4"
}
]
}
}

View File

@@ -0,0 +1,149 @@
{
"success": true,
"data": [
{
"id": 1,
"name": "The Witcher 3: Wild Hunt",
"image": "game1",
"text": "$10",
"imgPath": "img_top_1",
"description": "Эпическая RPG с открытым миром, в которой Геральт из Ривии охотится на монстров и раскрывает политические заговоры.",
"category": "RPG"
},
{
"id": 2,
"name": "Red Dead Redemption 2",
"image": "game2",
"text": "$10",
"imgPath": "img_top_2",
"description": "Приключенческая игра с открытым миром на Диком Западе, рассказывающая историю Артура Моргана.",
"category": "Adventures"
},
{
"id": 3,
"name": "Forza Horizon 5",
"image": "game3",
"text": "$10",
"imgPath": "img_top_3",
"description": "Гоночная игра с огромным открытым миром, действие которой происходит в Мексике.",
"category": "Race"
},
{
"id": 4,
"name": "Atomic Heart",
"image": "game4",
"text": "$10",
"imgPath": "img_top_4",
"description": "Экшен-шутер с элементами RPG, разворачивающийся в альтернативной Советской России.",
"category": "Shooters"
},
{
"id": 5,
"name": "Counter-Strike 2",
"image": "game5",
"text": "$10",
"imgPath": "img_top_5",
"description": "Популярный онлайн-шутер с соревновательным геймплеем и тактическими элементами.",
"category": "Shooters"
},
{
"id": 6,
"name": "Grand Theft Auto V",
"image": "game6",
"text": "$10",
"imgPath": "img_top_6",
"description": "Игра с открытым миром, где можно погрузиться в криминальный мир Лос-Сантоса.",
"category": "Adventures"
},
{
"id": 7,
"name": "Assassins Creed IV: Black Flag",
"image": "game7",
"text": "$10",
"imgPath": "img_top_7",
"description": "Приключенческая игра о пиратах и морских сражениях в эпоху золотого века пиратства.",
"category": "Adventures"
},
{
"id": 8,
"name": "Spider-Man",
"image": "game8",
"text": "$10",
"imgPath": "img_top_8",
"description": "Игра о супергерое Человеке-пауке с захватывающими битвами и паркуром по Нью-Йорку.",
"category": "Action"
},
{
"id": 9,
"name": "Assassins Creed Mirage",
"image": "game9",
"text": "$10",
"imgPath": "img_top_9",
"description": "Приключенческая игра с упором на скрытность, вдохновленная классическими частями серии.",
"category": "Action"
},
{
"id": 10,
"name": "Assassins Creed Valhalla",
"image": "game10",
"text": "$10",
"imgPath": "img_top_10",
"description": "RPG с открытым миром о викингах, включающая битвы, исследования и строительство поселений.",
"category": "RPG"
},
{
"id": 11,
"name": "ARK: Survival Evolved",
"image": "game11",
"text": "$10",
"imgPath": "img_top_11",
"description": "Выживание в открытом мире с динозаврами, строительством и многопользовательскими элементами.",
"category": "Simulators"
},
{
"id": 12,
"name": "FIFA 23",
"image": "game12",
"text": "$10",
"imgPath": "img_top_12",
"description": "Популярный футбольный симулятор с улучшенной графикой и реалистичным геймплеем.",
"category": "Sports"
},
{
"id": 13,
"name": "Dirt 5",
"image": "game13",
"text": "$10",
"imgPath": "img_top_13",
"description": "Аркадная гоночная игра с фокусом на ралли и внедорожных соревнованиях.",
"category": "Race"
},
{
"id": 14,
"name": "Cyberpunk 2077",
"image": "game14",
"text": "$10",
"imgPath": "img_top_14",
"description": "RPG в киберпанк-сеттинге с нелинейным сюжетом и детализированным открытым миром.",
"category": "RPG"
},
{
"id": 15,
"name": "Age of Empires IV",
"image": "game15",
"text": "$10",
"imgPath": "img_top_15",
"description": "Классическая стратегия в реальном времени с историческими кампаниями.",
"category": "Strategies"
},
{
"id": 16,
"name": "Civilization VI",
"image": "game16",
"text": "$10",
"imgPath": "img_top_16",
"description": "Глобальная пошаговая стратегия, в которой игроки строят и развивают цивилизации.",
"category": "Strategies"
}
]
}

View File

@@ -0,0 +1,119 @@
{
"success": true,
"data": {
"topSail": [
{
"image": "game1",
"text": "$10",
"imgPath": "img_top_1"
},
{
"image": "game2",
"text": "$10",
"imgPath": "img_top_2"
},
{
"image": "game3",
"text": "$10",
"imgPath": "img_top_3"
},
{
"image": "game4",
"text": "$10",
"imgPath": "img_top_4"
},
{
"image": "game5",
"text": "$10",
"imgPath": "img_top_5"
},
{
"image": "game6",
"text": "$10",
"imgPath": "img_top_6"
},
{
"image": "game7",
"text": "$10",
"imgPath": "img_top_7"
},
{
"image": "game8",
"text": "$10",
"imgPath": "img_top_8"
}
],
"categories": [
{
"image": "category1",
"text": "гонки",
"imgPath": "img_categories_1",
"category": "Race"
},
{
"image": "category2",
"text": "глубокий сюжет",
"imgPath": "img_categories_2",
"category": ""
},
{
"image": "category3",
"text": "симуляторы",
"imgPath": "img_categories_3",
"category": "Simulators"
},
{
"image": "category4",
"text": "открытый мир",
"imgPath": "img_categories_4",
"category": "RPG"
},
{
"image": "category5",
"text": "экшен",
"imgPath": "img_categories_5",
"category": "Action"
},
{
"image": "category6",
"text": "стратегии",
"imgPath": "img_categories_6",
"category": "Strategies"
},
{
"image": "category7",
"text": "шутеры",
"imgPath": "img_categories_7",
"category": "Shooters"
},
{
"image": "category8",
"text": "приключения",
"imgPath": "img_categories_8",
"category": "Adventures"
}
],
"news": [
{
"image": "news1",
"text": "Разработчики Delta Force: Hawk Ops представили крупномасштабный режим Havoc Warfare",
"imgPath": "img_news_1"
},
{
"image": "news2",
"text": "Первый трейлер Assassins Creed Shadows — с темнокожим самураем в феодальной Японии",
"imgPath": "img_news_2"
},
{
"image": "news3",
"text": "Призрак Цусимы» вышел на ПК — и уже ставит рекорды для Sony",
"imgPath": "img_news_3"
},
{
"image": "news4",
"text": "Авторы Skull and Bones расширяют планы на второй сезо",
"imgPath": "img_news_4"
}
]
}
}

View File

@@ -0,0 +1,37 @@
{
"success":true,
"data":
[
{
"id": 1,
"title": "Mortal Kombat 11",
"image": "mortal",
"alt": "Игра Мортал Комбат 11, картинка",
"releaseDate": "23 апр. 2019",
"description": "MORTAL KOMBAT 11 ULTIMATE ВКЛЮЧАЕТ В СЕБЯ БАЗОВУЮ ИГРУ МК11, КОМВАТ РАСК 1, ДОПОЛНЕНИЕ «ПОСЛЕДСТВИЯ» И НЕДАВНО ДОБАВЛЕННЫЙ НАБОР «КОМБАТ 2».",
"price": 300
},
{
"id": 2,
"title": "EA SPORTS™ FIFA 23",
"image": "fifa",
"alt": "Игра Фифа, картинка",
"releaseDate": "30 сен. 2022",
"description": "В FIFA 23 всемирная игра становится еще лучше с технологией HyperMotion2, мужским и женским FIFA World Cup™, женскими командами, кроссплатформенной игрой и множеством прочих возможностей.",
"price": 300
},
{
"id": 3,
"title": "Ведьмак: Дикая Охота",
"image": "ved",
"alt": "Игра Ведьмак, картинка",
"releaseDate": "18 мая 2015",
"description": "Вы — Геральт из Ривии, наемный убийца чудовищ. Вы путешествуете по миру, в котором бушует война и на каждом шагу подстерегают чудовища. Вам предстоит выполнить заказ и найти Цири — Дитя Предназначения, живое оружие, способное изменить облик этого мира.",
"price": 300
}
]
}

View File

@@ -1,103 +1,201 @@
const router = require('express').Router();
//const loginMiddleware = require('../middleware/login-middleware');
// First page
router.get('/getInfoAboutKazan', (request, response) => {
response.send(require('./json/first/info-about-kazan/success.json'))
})
const lang = request.query.lang || 'ru'; // Получаем язык из параметров запроса
try {
const data = require('./json/first/info-about-kazan/success.json'); // Загружаем весь JSON
const translatedData = data[lang] || data['ru']; // Выбираем перевод по языку или дефолтный
response.send(translatedData); // Отправляем перевод клиенту
} catch (error) {
response.status(500).send({ message: 'Internal server error' }); // Ошибка в случае проблем с JSON
}
});
router.get('/getNews', (request, response) => {
response.send(require('./json/first/news/success.json'))
const lang = request.query.lang || 'ru';
try {
const data = require(`./json/first/news/${lang}/success.json`);
response.send(data);
} catch (error) {
response.status(404).send({ message: 'Language not found' });
}
})
// Sport page
router.get('/getFirstText', (request, response) => {
const lang = request.query.lang || 'ru'; // Получаем язык из параметров
try {
const data = require('./json/sport/first-text/success.json'); // Загружаем JSON
const translatedData = data[lang] || data['ru']; // Берём перевод или дефолтный
response.send(translatedData);
} catch (error) {
response.status(404).send({ message: 'Language not found' }); // Обработка ошибки
}
});
router.get('/getSecondText', (request, response) => {
const lang = request.query.lang || 'ru';
try {
const data = require('./json/sport/second-text/success.json');
const translatedData = data[lang] || data['ru'];
response.send(translatedData);
} catch (error) {
response.status(404).send({ message: 'Language not found' });
}
});
router.get('/getSportData', (request, response) => {
response.send(require('./json/sport/sport-data.json'))
const lang = request.query.lang || 'ru';
try {
const data = require(`./json/sport/sport-list/${lang}/success.json`);
response.send(data);
} catch (error) {
response.status(404).send({ message: 'Language not found' });
}
})
// Places page
router.get('/getPlacesData', (request, response) => {
response.send(require('./json/places/places-data.json'))
const lang = request.query.lang || 'ru';
try {
const data = require(`./json/places/${lang}/success.json`);
response.send(data);
} catch (error) {
response.status(404).send({ message: 'Language not found' });
}
})
// Transport page
router.get('/getInfoAboutTransportPage', (request, response) => {
response.send(require('./json/transport/info-about-page.json'))
const lang = request.query.lang || 'ru';
try {
const data = require('./json/transport/info-about-page/success.json');
const translatedData = data[lang] || data['ru'];
response.send(translatedData);
} catch (error) {
response.status(404).send({ message: 'Language not found' });
}
})
router.get('/getBus', (request, response) => {
response.send(require('./json/transport/bus-numbers.json'))
response.send(require('./json/transport/bus-numbers/success.json'))
})
router.get('/getTral', (request, response) => {
response.send(require('./json/transport/tral-numbers.json'))
response.send(require('./json/transport/tral-numbers/success.json'))
})
router.get('/getEvents', (request, response) => {
response.send(require('./json/transport/events-calendar.json'))
response.send(require('./json/transport/events-calendar/success.json'))
})
router.get('/getTripSchedule', (request, response) => {
response.send(require('./json/transport/trip-schedule/success.json'))
const lang = request.query.lang || 'ru';
try {
const data = require(`./json/transport/trip-schedule/${lang}/success.json`);
response.send(data);
} catch (error) {
response.status(404).send({ message: 'Language not found' });
}
})
router.get('/getInfoAboutInstitutions', (request, response) => {
response.send(require('./json/transport/info-about-institutions.json'))
// History page
router.get('/getHistoryText', (request, response) => {
const lang = request.query.lang || 'ru';
try {
const data = require(`./json/history/text/${lang}/success.json`);
response.send(data);
} catch (error) {
response.status(404).send({ message: 'Language not found' });
}
})
router.get('/getHistoryList', (request, response) => {
const lang = request.query.lang || 'ru';
try {
const data = require(`./json/history/list/${lang}/success.json`);
response.send(data);
} catch (error) {
response.status(404).send({ message: 'Language not found' });
}
})
// Education page
router.get('/getInfoAboutKFU', (request, response) => {
response.send(require('./json/education/info-about-kfu.json'))
router.get('/getInfoAboutEducation', (request, response) => {
const lang = request.query.lang || 'ru';
try {
const data = require('./json/education/text/success.json');
const translatedData = data[lang] || data['ru'];
response.send(translatedData);
} catch (error) {
response.status(404).send({ message: 'Language not found' });
}
})
router.get('/getEducationList', (request, response) => {
const lang = request.query.lang || 'ru';
try {
const data = require(`./json/education/cards/${lang}/success.json`);
response.send(data);
} catch (error) {
response.status(404).send({ message: 'Language not found' });
}
})
router.get('/getInfoAboutKFU', (request, response) => {
const lang = request.query.lang || 'ru';
try {
const data = require('./json/education/kfu/success.json');
const translatedData = data[lang] || data['ru'];
response.send(translatedData);
} catch (error) {
response.status(404).send({ message: 'Language not found' });
}
})
// Login
router.post('/entrance', (request, response) => {
const { email, password } = request.body.entranceData;
try {
const users = require('../json/users-information/success.json');
const user = users.data.find(user => user.email === email && user.password === password);
if (!user) {
return response.status(401).send('Неверные учетные данные');
}
const responseObject = {
email: user.email,
}
if (user.cardId){
responseObject.cardId = user.cardId || "";
}
return response.json(responseObject);
const users = require('./json/users-information/success.json');
const user = users.data.find(user => user.email === email && user.password === password);
if (!user) {
return response.status(401).send('Неверные учетные данные');
}
const responseObject = {
email: user.email,
}
return response.json(responseObject);
} catch (error) {
console.error('Ошибка чтения файла:', error);
response.status(500).send('Внутренняя ошибка сервера');
console.error('Ошибка чтения файла:', error);
response.status(500).send('Внутренняя ошибка сервера');
}
})
router.post('/registration', async (request, response) => {
const { email, password, confirmPassword } = request.body.registerData;
try {
if (password !== confirmPassword) {
return response.status(400).send('Пароли не совпадают!');
}
const users = require('../json/users-information/success.json');
const existingUser = users.data.find(user => user.email === email);
if (existingUser) {
return response.status(400).send('Пользователь с такой почтой уже существует!');
}
return response.json({ email: email});
} catch (error) {
console.error('Ошибка регистрации пользователя:', error);
response.status(500).send('Внутренняя ошибка сервера');
}
});
})
router.post('/registration', async (request, response) => {
const { email, password, confirmPassword } = request.body.registerData;
try {
if (password !== confirmPassword) {
return response.status(400).send('Пароли не совпадают!');
}
const users = require('./json/users-information/success.json');
const existingUser = users.data.find(user => user.email === email);
if (existingUser) {
return response.status(400).send('Пользователь с такой почтой уже существует!');
}
return response.json({ email: email });
} catch (error) {
console.error('Ошибка регистрации пользователя:', error);
response.status(500).send('Внутренняя ошибка сервера');
}
});
module.exports = router;

View File

@@ -0,0 +1,26 @@
[
{
"id": "1",
"image": "img1",
"title": "Preschool and School Education",
"text": "Kazan has more than 300 preschool institutions that provide comprehensive development for children from an early age. School education in the city is of a high standard, as evidenced by the results of graduation exams and competitions. Many programs are implemented in Kazan to support talented students, including specialized schools and advanced subject studies."
},
{
"id": "2",
"image": "img2",
"title": "Secondary and Higher Education",
"text": "Kazan is home to prestigious secondary specialized educational institutions that train mid-level specialists for various industries. The city is a major educational hub with over 20 higher educational institutions, including some of Russia's leading universities. Kazan's universities offer a wide range of educational programs that meet modern labor market demands."
},
{
"id": "3",
"image": "img3",
"title": "Science",
"text": "Kazan is one of Russia's leading scientific centers, hosting numerous research institutes and academic institutions. The city organizes major scientific conferences and forums that attract scientists from around the world. Kazan researchers have achieved significant success in various fields, including chemistry, physics, medicine, and information technology."
},
{
"id": "4",
"image": "img4",
"title": "Innovations",
"text": "Kazan is a leader in innovations in Russia. The city is home to major tech companies and startups that develop and implement innovative solutions. Currently, Tatarstan hosts the largest industrial and manufacturing special economic zone in Russia, 'Alabuga,' 4 industrial parks, the 'Himgrad' technopolis, 14 technology parks, and an IT park."
}
]

View File

@@ -0,0 +1,27 @@
[
{
"id": "1",
"image": "img1",
"title": "Дошкольное и школьное образование",
"text": "В Казани насчитывается более 300 дошкольных учреждений, обеспечивающих всестороннее развитие детей с раннего возраста. Школьное образование в городе отличается высоким уровнем, о чем свидетельствуют результаты выпускных экзаменов и олимпиад. В Казани реализуется множество программ по поддержке талантливых школьников, включая специализированные школы и углубленное изучение предметов."
},
{
"id": "2",
"image": "img2",
"title": "Среднее и высшее образование",
"text": "В Казани расположены престижные средние специальные учебные заведения, готовящие специалистов среднего звена для различных отраслей. Город является крупным образовательным центром с более чем 20 высшими учебными заведениями, в том числе ведущими университетами России. Казанские вузы предлагают широкий спектр образовательных программ, отвечающих современным требованиям рынка труда."
},
{
"id": "3",
"image": "img3",
"title": "Наука",
"text": "Казань является одним из ведущих научных центров России, где сосредоточены многочисленные научно-исследовательские институты и академические учреждения. В городе проводятся крупные научные конференции и форумы, привлекающие ученых со всего мира. Казанские ученые добились значительных успехов в различных областях, включая химию, физику, медицину и информационные технологии."
},
{
"id": "4",
"image": "img4",
"title": "Инновации",
"text": "Казань является одним из лидеров в сфере инноваций в России. В городе работают крупные технологические компании и стартапы, разрабатывающие и внедряющие инновационные решения. В настоящее время в Татарстане действуют: крупнейшая в России особая экономическая зона промышленно-производственного типа «Алабуга», 4 индустриальных парка, технополис «Химград», 14 технопарков, IT-парк."
}
]

View File

@@ -0,0 +1,26 @@
[
{
"id": "1",
"image": "img1",
"title": "Мәктәпкәчә һәм мәктәп белем бирү",
"text": "Казанда 300дән артык мәктәпкәчә белем бирү учреждениесе бар, алар балаларны кечкенәдән үстерү өчен шартлар тудыра. Мәктәп белем бирүе югары дәрәҗәдә булуы белән аерылып тора, бу чыгарылыш имтиханнары һәм олимпиадалар нәтиҗәләреннән күренә. Казанда талантлы укучыларга ярдәм итү буенча махсус программалар гамәлгә ашырыла, шул исәптән профильле мәктәпләр һәм фәннәрне тирәнтен өйрәнү мөмкинлекләре."
},
{
"id": "2",
"image": "img2",
"title": "Урта һәм югары белем бирү",
"text": "Казанда төрле тармаклар өчен урта звено белгечләрен әзерләүче абруйлы урта махсус уку йортлары урнашкан. Шәһәр 20дән артык югары уку йорты булган зур белем бирү үзәге булып тора, шул исәптән Россиянең алдынгы университетлары. Казан университетлары хезмәт базары таләпләренә туры килгән киң белем бирү программалары тәкъдим итә."
},
{
"id": "3",
"image": "img3",
"title": "Фән",
"text": "Казан Россиянең әйдәп баручы фәнни үзәкләренең берсе, монда күпсанлы фәнни-тикшеренү институтлары һәм академик учреждениеләр тупланган. Шәһәрдә бөтен дөньядан галимнәрне җәлеп итүче зур фәнни конференцияләр һәм форумнар үткәрелә. Казан галимнәре химия, физика, медицина һәм мәгълүмати технологияләр кебек төрле өлкәләрдә зур уңышларга иреште."
},
{
"id": "4",
"image": "img4",
"title": "Инновацияләр",
"text": "Казан Россиядә инновацияләр өлкәсе лидеры. Шәһәрдә зур технологик компанияләр һәм стартаплар эшләп килә, алар инновацион карарлар эшли һәм гамәлгә кертә. Татарстанда Россиянең иң зур сәнәгать-җитештерү махсус икътисади зонасы «Алабуга», 4 индустриаль парк, «Химград» технополисы, 14 технопарк һәм IT-парк эшли."
}
]

View File

@@ -1,4 +0,0 @@
[
"Казанский (Приволжский) федеральный университет (полное наименование — федеральное государственное автономное образовательное учреждение высшего образования «Казанский (Приволжский) федеральный университет», тат. Казан (Идел буе) федераль университеты) — высшее учебное заведение в Казани, один из старейших российских университетов (основан в 1804 году) и один из десяти федеральных университетов (с 2010 года).",
"В состав университетского учебно-научного комплекса входят научная библиотека, научно-исследовательские институты химии, математики и механики, 7 музеев, ботанический сад, астрономические обсерватории, центр информационных технологий, издательство, центр и лаборатория оперативной полиграфии, культурно-спортивный комплекс, спортивно-оздоровительный лагерь и другие подразделения."
]

View File

@@ -0,0 +1,23 @@
{
"ru": {
"title": "Kазанский федеральный университет",
"description": [
"Казанский (Приволжский) федеральный университет (полное наименование — федеральное государственное автономное образовательное учреждение высшего образования «Казанский (Приволжский) федеральный университет», тат. Казан (Идел буе) федераль университеты) — высшее учебное заведение в Казани, один из старейших российских университетов (основан в 1804 году) и один из десяти федеральных университетов (с 2010 года).",
"В состав университетского учебно-научного комплекса входят научная библиотека, научно-исследовательские институты химии, математики и механики, 7 музеев, ботанический сад, астрономические обсерватории, центр информационных технологий, издательство, центр и лаборатория оперативной полиграфии, культурно-спортивный комплекс, спортивно-оздоровительный лагерь и другие подразделения."
]
},
"en": {
"title": "Kazan Federal University",
"description": [
"Kazan (Volga Region) Federal University (full name - Federal State Autonomous Educational Institution of Higher Education 'Kazan (Volga Region) Federal University') is a higher educational institution in Kazan, one of the oldest Russian universities (founded in 1804) and one of the ten federal universities (since 2010).",
"The university's educational and research complex includes a scientific library, research institutes of chemistry, mathematics, and mechanics, 7 museums, a botanical garden, astronomical observatories, an information technology center, a publishing house, a center and laboratory for operational printing, a cultural and sports complex, a sports and recreation camp, and other divisions."
]
},
"tt": {
"title": "Казан Федераль Университеты",
"description": [
"Казан (Идел буе) федераль университеты (тулы исеме — Казан (Идел буе) федераль университеты) Казан шәһәрендә урнашкан. Ул 1804 елда нигезләнгән, Россиянең иң борынгы университетларының берсе һәм 2010 елдан бирле ун федераль университетларның берсе булып тора.",
"Университетның уку-укыту һәм фәнни комплексына фәнни китапханә, химия, математика һәм механика буенча фәнни-тикшеренү институтлары, 7 музей, ботаник бакча, астрономия обсерваторияләре, мәгълүмат технологияләре үзәге, нәшрият, оператив полиграфия үзәге һәм лабораториясе, мәдәни-спорт комплексы, спорт-сәламәтләндерү лагере һәм башка бүлекләр керә."
]
}
}

View File

@@ -0,0 +1,11 @@
{
"ru": {
"text": "Казань один из крупнейших университетских городов России исторически сформировался как центр знаний и науки. Ежегодно в нашем городе выпускается более 4 тыс. специалистов технического профиля и, что особенно важно, многие из них талантливые разработчики и носители новых идей."
},
"en": {
"text": "Kazan, one of the largest university cities in Russia, has historically emerged as a center of knowledge and science. Every year, our city graduates more than 4 thousand technical specialists and, what is especially important, many of them are talented developers and bearers of new ideas."
},
"tt": {
"text": "Рәсәйнең иң зур университет шәһәрләренең берсе булган Казан тарихта белем һәм фән үзәге булып барлыкка килде. Ел саен безнең шәһәр 4 меңнән артык техник белгечне тәмамлый, һәм иң мөһиме, аларның күбесе сәләтле уйлап табучылар һәм яңа идеялар алып баручылар."
}
}

View File

@@ -1,3 +1,11 @@
[
"Казань — древний город с богатой историей, где слились воедино культуры Востока и Запада. Подобно драгоценному камню, сияющему в ожерелье городов России, Казань покоряет своей красотой и многообразием. Её красивая архитектура и гостеприимные жители создают уютную атмосферу, привлекающую туристов со всего мира."
]
{
"ru": {
"description": "Казань — древний город с богатой историей, где слились воедино культуры Востока и Запада. Подобно драгоценному камню, сияющему в ожерелье городов России, Казань покоряет своей красотой и многообразием. Её красивая архитектура и гостеприимные жители создают уютную атмосферу, привлекающую туристов со всего мира."
},
"en": {
"description": "Kazan is an ancient city with a rich history, where the cultures of East and West merged together. Like a precious stone shining in the necklace of Russian cities, Kazan captivates with its beauty and diversity. Its beautiful architecture and hospitable residents create a cozy atmosphere that attracts tourists from all over the world."
},
"tt": {
"description": "Казан - борыңгы шәһәр, анда Көнчыгыш һәм Көнбатыш культуралары берләшкән, Рәсәй шәһәрләренең муенсасында балкып торган кыйммәтле таш кебек, Казан үзенең матур архитектурасы һәм кунакчыллыгы белән уңайлы бөтен дөньядан туристларны җәлеп итә торган атмосфера."
}
}

View File

@@ -0,0 +1,32 @@
[
{
"id": "1",
"image": "new1",
"title": "Evacuation announced at enterprises in Kazan",
"text": "In Kazan, evacuation has been announced at several enterprises. This was reported by the press service of the head of Tatarstan. 'In some areas of Kazan, the need for evacuation at enterprises has been announced,' the press service of the head of Tatarstan said. The information was provided by TASS. The Telegram channel Shot reports the evacuation of employees of the chemical company Kazanorgsintez."
},
{
"id": "2",
"image": "new2",
"title": "Interaction of children with gadgets discussed in Kazan",
"text": "A conference dedicated to the challenges of parenting in the era of technological progress was held in Kazan. Participants, including psychologists, educators, and parents, discussed methods to combat gadget addiction and ways to use technology for youth development. 'There is nothing wrong with a child using a phone. The main thing is to guide them properly,' shared Alfia Valeeva, a teacher with 16 years of experience."
},
{
"id": "3",
"image": "new3",
"title": "Kazan UNICS lost to CSKA, series score 0-3",
"text": "In the third match of the VTB United League finals, CSKA proved stronger than UNICS on their home court with a score of 80:72. The series score became 3-0 in favor of CSKA. If CSKA wins one more time, they will become champions. Unlike the previous game, the Kazan team started confidently. They won the first quarter 17:13 and led 21:13 at the start of the second. However, CSKA quickly leveled the score and then took the lead."
},
{
"id": "4",
"image": "new4",
"title": "Forecasters warn of thunderstorm and strong winds in Kazan",
"text": "This evening, thunderstorms and strong southwest winds with gusts of 1520 m/s, and in some areas up to 23 m/s, are expected in Tatarstan, including Kazan. This warning was issued by the RT Hydrometeorological Center."
},
{
"id": "5",
"image": "new5",
"title": "Additional trains to run between the capital of Tatarstan and the airport",
"text": "Additional commuter trains will run on the Kazan Airport Kazan route for two days. This is due to concerts being held at the Kazan Expo Exhibition Center. The additional trains will operate without intermediate stops, according to the press service of JSC 'Sodruzhestvo'."
}
]

View File

@@ -0,0 +1,32 @@
[
{
"id": "1",
"image": "new1",
"title": "На предприятиях в Казани объявили эвакуацию",
"text": "В Казани на некоторых предприятиях объявлена необходимость эвакуации. Об этом сообщили в пресс-службе главы Татарстана. «В отдельных районах Казани на предприятиях объявлена необходимость эвакуации», — сообщили в пресс-службе главы Татарстана. Информацию передает ТАСС. Telegram-канал Shot пишет об эвакуации сотрудников химической компании «Казаньоргсинтез»."
},
{
"id": "2",
"image": "new2",
"title": "В Казани обсудили взаимодействие детей с гаджетами",
"text": "В Казани состоялась конференция, посвящённая проблемам воспитания в эпоху технического прогресса. Участники встречи, среди которых психологи, педагоги и родители, обсудили методы противодействия гаджетозависимости и возможности использования технологий для развития молодёжи. «Ничего плохого нет в том, что ребёнок сидит в телефоне. Главное — правильно его направить», - поделилась своим опытом Альфия Валеева, педагог с 16-летним стажем."
},
{
"id": "3",
"image": "new3",
"title": "Казанский УНИКС проиграл ЦСКА, счёт в серии 0-3",
"text": "В третьем матче финала Единой лиги ВТБ ЦСКА на своей площадке оказался сильнее УНИКСа — 80:72. Счет в серии стал 30 в пользу ЦСКА. Если армейцы выиграют еще раз, то станут чемпионами. В отличие от предыдущей игры казанцы уверенно начали. Первую четверть они выиграли 17:13, а на старте второй вели 21:13. Однако ЦСКА быстро сравнял счет, а затем вышел вперед. "
},
{
"id": "4",
"image": "new4",
"title": "Синоптики предупредили о грозе и сильном ветре в Казани",
"text": "Сегодня вечером в Татарстане, включая Казань, ожидаются гроза и сильный юго-западный ветер порывами 1520 м/с, местами до 23 м/с. Об этом предупреждает Гидрометцентр РТ."
},
{
"id": "5",
"image": "new5",
"title": "Между столицей РТ и аэропортом запустят дополнительные рейсы",
"text": "На маршруте Казань Аэропорт Казань два дня будут курсировать дополнительные пригородные поезда. Это связано с проведением концертов в МВЦ «Казань Экспо». Дополнительные поезда проследуют без промежуточных остановок, сообщили в пресс-службе АО «Содружество»."
}
]

View File

@@ -1,32 +0,0 @@
[
{
"id": "1",
"image": "new1",
"title": "На предприятиях в Казани объявили эвакуацию",
"text": "В Казани на некоторых предприятиях объявлена необходимость эвакуации. Об этом сообщили в пресс-службе главы Татарстана. «В отдельных районах Казани на предприятиях объявлена необходимость эвакуации», — сообщили в пресс-службе главы Татарстана. Информацию передает ТАСС. Telegram-канал Shot пишет об эвакуации сотрудников химической компании «Казаньоргсинтез»."
},
{
"id": "2",
"image": "new2",
"title": "В Казани обсудили взаимодействие детей с гаджетами",
"text": "В Казани состоялась конференция, посвящённая проблемам воспитания в эпоху технического прогресса. Участники встречи, среди которых психологи, педагоги и родители, обсудили методы противодействия гаджетозависимости и возможности использования технологий для развития молодёжи. «Ничего плохого нет в том, что ребёнок сидит в телефоне. Главное — правильно его направить», - поделилась своим опытом Альфия Валеева, педагог с 16-летним стажем."
},
{
"id": "3",
"image": "new3",
"title": "Казанский УНИКС проиграл ЦСКА, счёт в серии 0-3",
"text": "В третьем матче финала Единой лиги ВТБ ЦСКА на своей площадке оказался сильнее УНИКСа — 80:72. Счет в серии стал 30 в пользу ЦСКА. Если армейцы выиграют еще раз, то станут чемпионами. В отличие от предыдущей игры казанцы уверенно начали. Первую четверть они выиграли 17:13, а на старте второй вели 21:13. Однако ЦСКА быстро сравнял счет, а затем вышел вперед. "
},
{
"id": "4",
"image": "new4",
"title": "Синоптики предупредили о грозе и сильном ветре в Казани",
"text": "Сегодня вечером в Татарстане, включая Казань, ожидаются гроза и сильный юго-западный ветер порывами 1520 м/с, местами до 23 м/с. Об этом предупреждает Гидрометцентр РТ."
},
{
"id": "5",
"image": "new5",
"title": "Между столицей РТ и аэропортом запустят дополнительные рейсы",
"text": "На маршруте Казань Аэропорт Казань два дня будут курсировать дополнительные пригородные поезда. Это связано с проведением концертов в МВЦ «Казань Экспо». Дополнительные поезда проследуют без промежуточных остановок, сообщили в пресс-службе АО «Содружество»."
}
]

View File

@@ -0,0 +1,32 @@
[
{
"id": "1",
"image": "new1",
"title": "Казанда предприятиеләрдә эвакуация игълан ителгән",
"text": "Казанда кайбер предприятиеләрдә эвакуация таләп ителгән. Бу хакта Татарстан җитәкчесенең матбугат хезмәте хәбәр итте. 'Казанның аерым районнарында предприятиеләрдә эвакуация таләп ителә', — дип белдерде Татарстан җитәкчесенең матбугат хезмәте. Мәгълүматны ТАСС җиткерә. Shot Telegram-каналы 'Казаноргсинтез' химия компаниясе хезмәткәрләренең эвакуациясе турында хәбәр итә."
},
{
"id": "2",
"image": "new2",
"title": "Казанда балаларның гаджетлар белән эшләвен тикшерделәр",
"text": "Казанда техник прогресс чорында тәрбия проблемаларына багышланган конференция узды. Психологлар, педагоглар һәм ата-аналар катнашында үткән чарада гаджетларга бәйлелеккә каршы чаралар һәм яшьләрне үстерү өчен технологияләрне куллану мөмкинлекләре турында фикер алыштылар. 'Баланың телефонда утыруында бернинди начар нәрсә юк. Иң мөһиме — аны дөрес юнәлешкә юнәлтү', — дип үз тәҗрибәсе белән уртаклашты 16 ел стажлы педагог Альфия Вәлиева."
},
{
"id": "3",
"image": "new3",
"title": "Казан УНИКСы ЦСКАга җиңелде, сериядә исәп 0-3",
"text": "VTB Берләшкән лигасының финалындагы өченче матчта ЦСКА үз мәйданында УНИКСтан өстен чыкты — 80:72. Сериядә исәп 30 ЦСКА файдасына. Әгәр армиячеләр тагын бер җиңүгә ирешсәләр, чемпион булалар. Алдагы уен белән чагыштырганда, казанлылар ышанычлырак башладылар. Беренче кварталны алар 17:13 исәбе белән отты, ә икенче квартал башында 21:13 белән алда бардылар. Әмма ЦСКА тиз арада исәпне тигезләде һәм аннары алга чыкты."
},
{
"id": "4",
"image": "new4",
"title": "Синоптиклар Казанда яшен һәм көчле җил турында кисәтә",
"text": "Бүген кич Татарстанда, шул исәптән Казанда, яшен һәм 1520 м/с, кайбер урыннарда 23 м/с тизлектә көньяк-көнбатыш җил көтелә. Бу хакта ТР Гидрометеоүзәге кисәтә."
},
{
"id": "5",
"image": "new5",
"title": "Татарстан башкаласы белән аэропорт арасында өстәмә рейслар оештырыла",
"text": "Казан Аэропорт Казан маршруты буенча ике көн дәвамында өстәмә шәһәр яны поездлары йөриячәк. Бу Казан Экспо күргәзмә үзәгендә концертлар үткәрү белән бәйле. Өстәмә поездлар тукталышларсыз йөриячәк, дип хәбәр итә 'Содружество' АҖнең матбугат хезмәте."
}
]

View File

@@ -0,0 +1,43 @@
[
{
"head": "History of Kazan",
"title": "The official founding date of Kazan is considered to be 1005",
"content": "The city emerged on the Volga River, at the intersection of trade routes between the East and the West."
},
{
"title": "In 1236, these lands were conquered by the troops of Batu Khan",
"content": "With the incorporation of Volga Bulgaria into the administrative system of the Golden Horde, Kazan's role as a border fortress diminished, and trade routes shifted. The defensive role of the stone fortress declined, while Kazan gained greater independence during this period."
},
{
"title": "In 1438, Kazan was captured by Khan Ulugh Muhammad, forming a new state the Kazan Khanate",
"content": "Torn by internal conflicts, the Golden Horde gradually lost its former power and fragmented into separate states."
},
{
"title": "On October 2, 1552, Kazan was captured by Ivan the Terrible",
"content": "After a seven-week siege by a 150,000-strong army, Kazan was taken by storm. This marked the beginning of a new chapter in Kazan's history, as part of the Tsardom of Russia, later the Russian Empire, and the USSR."
},
{
"title": "In 1708, Kazan became the capital of the vast Kazan Governorate",
"content": "As a result of Peter I's reforms, the Russian Empire was divided into eight governorates. The territory of Kazan Governorate was vast, including the voivodeships of Sviyazhsk, Penza, Simbirsk, Ufa, and Astrakhan. Over time, many of them became separate governorates."
},
{
"title": "In 1774, the city was stormed by the troops led by the fugitive Don Cossack Yemelyan Pugachev",
"content": "The rebel troops entered Kazan. Only the Kremlin remained under the control of government forces. However, after a massive fire broke out in Kazan, Pugachev ordered his troops to leave the city. Three days later, his forces were defeated on the Arsk Field."
},
{
"title": "In 1805, Kazan Imperial University was ceremonially opened",
"content": "It became the third most important university in the empire by significance and founding date. For a long period, it was also the easternmost university in the country."
},
{
"title": "In 1918, Kazan briefly became the epicenter of events on the Eastern Front",
"content": "The city changed hands between the Czech legionnaires, the White Army, and the Red Army. Surviving telegrams from Vladimir Lenin of that time highlight the importance attributed to capturing Kazan."
},
{
"title": "With the collapse of the USSR, the national movement in the republic gained momentum, culminating in the creation of the Republic of Tatarstan in 1990, with Kazan as its capital",
"content": "The newfound autonomy of the Republic of Tatarstan from the center and the associated redistribution of financial flows led to economic growth. Several large-scale programs implemented in the 1990s improved the quality of life for city residents."
},
{
"title": "In 2005, the city grandly celebrated its millennium",
"content": "An important milestone in the city's history was the preparation for the celebration of Kazan's Millennium. Several new facilities were built in the years leading up to this date."
}
]

View File

@@ -0,0 +1,43 @@
[
{
"head": "История возникновения Казани",
"title": "Официальной датой основания Казани считается  1005 год",
"content": "Город возник на Волге, на пересечении торговых маршрутов между Востоком и Западом."
},
{
"title": "В 1236 году данные земли завоевали войска хана Батыя",
"content": "С включением Волжской Булгарии административную систему Золотой Орды роль Казани как приграничной крепости была утрачена, изменились и торговые пути. Упала защитная роль каменной крепости, а Казань приобрела в тот период большую самостоятельность."
},
{
"title": "В 1438 году Казань захвачена ханом Улуг-Мухамедом, образуется новое государство - Казанское ханство",
"content": "Раздираемая междоусобицами, Золотая Орда со временем растеряла свое былое могущество, распавшись на ряд отдельных государств."
},
{
"title": "Второго октября 1552 года Казань была захвачена Иваном Грозным",
"content": "После семинедельной осады 150-тысячным войском, Казань была взята штурмом. Начинается новая история города Казани, теперь в Московском царстве, а позднее в Российской империи и СССР."
},
{
"title": "В 1708 году Казань становится столицей огромной Казанской губернии",
"content": "В результате реформ Петра I Российская империя была разделена на 8 губерний. Территория Казанской губернии была огромной и включала воеводства: Свияжское, Пензенское, Симбирское, Уфимское и Астраханское. В дальнейшем многие из них стали отдельными губерниями."
},
{
"title": "В 1774 году город штурмуют войска под предводительством беглого донского казака Емельяна Пугачева",
"content": "Войска повстанцев зашли в Казань. Под контролем правительственных войск остался лишь Кремль. Однако после того, как в Казани случился сильный пожар, Пугачеву пришлось отдать приказ воинам выйти из города. Спустя три дня его войска были разбиты на Арском поле."
},
{
"title": "В 1805 году торжественно открывается Казанский Императорский университет",
"content": "Он стал 3 во всей империи по значению и времени основания. Длительный период ВУЗ также был наиболее восточным в стране"
},
{
"title": "В 1918 году Казань на время стала эпицентром событий на Восточном фронте",
"content": "Город переходит из рук чешских легионеров и белой армии в руки красных и обратно. Сохранившиеся телеграммы Владимира Ленина тех лет показывают какое значение придавалось взятию Казани."
},
{
"title": "С распадом СССР в республике начинается подъем национального движения, закончившийся созданием в 1990 году Республики Татарстан в составе Российской Федерации, столицей которой становится Казань",
"content": "С обретением Республикой Татарстан определенной независимости от центра и связанным с этим перераспределением финансовых потоков связан подъем экономики. В 90-е годы прошлого столетия было реализовано несколько масштабных программ, приведших к повышению качества жизни горожан."
},
{
"title": "В 2005 году в мегаполисе с огромным размахом был отмечен миллениум",
"content": "Важной вехой в жизни города стала подготовка к празднованию Тысячелетия Казани. За несколько лет, предшествовавших этой дате были построены новые объекты."
}
]

View File

@@ -0,0 +1,43 @@
[
{
"head": "Казан тарихы",
"title": "Казанның нигез салыну датасы 1005 ел",
"content": "Шәһәр Идел елгасы буенда, Көнчыгыш белән Көнбатышны тоташтыручы сәүдә юллары киселешендә барлыкка килгән."
},
{
"title": "1236 елда бу җирләрне Батый хан гаскәрләре яулап ала",
"content": "Идел Болгарстаны Алтын Урда административ системасына кертелгәч, Казанның чик буе ныгытмасы буларак әһәмияте кими, сәүдә юллары үзгәрә. Шул чорда таш ныгытманың саклау функциясе югала, әмма Казан үзенең мөстәкыйльлеген арттыра."
},
{
"title": "1438 елда Казанны Улуг-Мөхәммәт хан яулап ала, һәм яңа дәүләт Казан ханлыгы барлыкка килә",
"content": "Алтын Урда эчке низаглар аркасында элекке куәтен югалта һәм төрле аерым дәүләтләргә бүленеп бетә."
},
{
"title": "1552 елның 2 октябрендә Казан Иван Грозный тарафыннан яулап алына",
"content": "Җиде атналык камау нәтиҗәсендә 150 меңлек гаскәр Казанны штурм белән ала. Казанның Мәскәү дәүләте, соңрак Россия империясе һәм ССРБ тарихына кергән яңа чоры башлана."
},
{
"title": "1708 елда Казан зур Казан губернасының башкаласына әйләнә",
"content": "Петр I реформалары нәтиҗәсендә Россия империясе 8 губернага бүленә. Казан губернасының территориясе киң була, ул Свияжск, Пенза, Симбирск, Уфа һәм Астрахань воеводалыкларын үз эченә ала. Соңрак алар аерым губерналарга әйләнә."
},
{
"title": "1774 елда шәһәргә Емельян Пугачев җитәкчелегендәге качак Дон казаклары гаскәрләре һөҗүм итә",
"content": "Фетнәчеләр Казанга керә. Хөкүмәт гаскәрләре контролендә Кремль генә кала. Әмма шәһәрдә зур янгын чыкканнан соң, Пугачев үз гаскәрләренә шәһәрдән чыгуны боера. Өч көннән соң, аның гаскәрләре Арча кырында тар-мар ителә."
},
{
"title": "1805 елда Казан Император университеты тантаналы рәвештә ачыла",
"content": "Бу университет империядә әһәмияте һәм оешу вакыты буенча өченче була. Ул озак вакыт дәвамында илдәге иң көнчыгыш университет булып тора."
},
{
"title": "1918 елда Казан Көнчыгыш фронт вакыйгаларының үзәгенә әйләнә",
"content": "Шәһәр Чех легионерлары, аклар һәм кызыллар кулына чиратлашып күчә. Владимир Ленинның шул чордагы телеграммалары Казанны алуның никадәр мөһим булганын күрсәтә."
},
{
"title": "ССРБ таркалгач, 1990 елда Татарстан Республикасы төзелә, аның башкаласы Казан була",
"content": "Татарстан Республикасы үзәккә карата мөстәкыйльлек алуга ирешә. Бу финанс агымнарының яңача бүленүенә китерә, һәм шәһәрдә икътисади үсеш башлана. Узган гасырның 90нчы елларында шәһәр халкының тормыш сыйфатын күтәрүгә юнәлдерелгән берничә зур программа гамәлгә ашырыла."
},
{
"title": "2005 елда Казан меңьеллыгын зур тантана белән билгеләп үтә",
"content": "Казанның Меңьеллыгын бәйрәм итүгә әзерлек шәһәр тарихында мөһим вакыйга булды. Әлеге датадан алда берничә ел эчендә яңа объектлар төзелде."
}
]

View File

@@ -0,0 +1,10 @@
{
"first": "Kazan is one of the largest cultural centers in Russia, preserving classical achievements while also promoting the development of modern, avant-garde directions in many areas of culture. The capital of Tatarstan is traditionally called 'multicultural,' implying the mutually enriching coexistence of Russian and Tatar cultures.",
"second": {
"head": "Culture",
"body": [
"The republic is home to peoples with different historical backgrounds and cultural traditions. The combination of at least three types of cultural interactions (Turkic, Slavic-Russian, and Finno-Ugric) defines the uniqueness of these places, as well as the originality of their cultural and historical values.",
"Tatarstan is associated with the fates of many outstanding cultural figures: singer Fyodor Chaliapin, writers Leo Tolstoy, Sergey Aksakov, and Maxim Gorky, Vasily Aksyonov, poets Yevgeny Baratynsky, Gavriil Derzhavin, Marina Tsvetaeva, and Nikita Zabolotsky, artists Ivan Shishkin and Nikolay Feshin. The classic of Tatar poetry Gabdulla Tukay, hero-poet Musa Jalil, composers Farid Yarullin, Salikh Saidashev, Nazib Zhiganov, Sofia Gubaidulina, and many others brought glory to Tatar culture."
]
}
}

View File

@@ -0,0 +1,10 @@
{
"first": "Казань является одним из крупнейших культурных центров России, сохраняя классические достижения, а также способствуя развитию современных, авангардных направлений во многих областях культуры. Столицу Татарстана традиционно называют «мультикультурной», подразумевая взаимовыгодное обогащение мирно сосуществующих русской и татарской культур.",
"second": {
"head": "Культура",
"body": [
"В республике проживают народы с разным историческим прошлым и культурными традициями. Сочетание по крайней мере трёх типов культурных взаимовлияний (тюркского, славяно-русского и финно-угорского) определяет уникальность этих мест, своеобразие культурных и исторических ценностей.",
"С Татарстаном связаны судьбы многих выдающихся деятелей культуры: певца Фёдора Шаляпина, писателей Льва Толстого, Сергея Аксакова и Максима Горького, Василия Аксёнова, поэтов Евгения Боратынского, Гавриила Державина, Марины Цветаевой и Никиты Заболоцкого, художников Ивана Шишкина и Николая Фешина. Классик татарской поэзии Габдулла Тукай, поэт-герой Муса Джалиль, композиторы Фарид Яруллин, Салих Сайдашев, Назиб Жиганов, София Губайдулина и многие другие составили славу татарской культуры."
]
}
}

View File

@@ -0,0 +1,10 @@
{
"first": "Казан Россиянең иң зур мәдәни үзәкләренең берсе булып тора, классик казанышларны саклап кына калмыйча, мәдәниятнең күп төрле өлкәләрендә заманча, авангард юнәлешләрне үстерүгә дә булышлык итә. Татарстан башкаласын традицион рәвештә «мультикультуралы» дип атыйлар, бу тыныч яшәүче рус һәм татар мәдәниятләренең үзара баетылуын аңлата.",
"second": {
"head": "Мәдәният",
"body": [
"Республикада төрле тарихи үткәне һәм мәдәни традицияләре булган халыклар яши. Өч төп мәдәни үзара йогынты (төрки, славян-рус һәм фин-угор) кушылуы әлеге төбәкләрнең уникальлеген, мәдәни һәм тарихи кыйммәтләрнең үзенчәлеген билгели.",
"Татарстан белән күп күренекле мәдәният эшлеклеләренең язмышлары бәйле: җырчы Фёдор Шаляпин, язучылар Лев Толстой, Сергей Аксаков һәм Максим Горький, Василий Аксёнов, шагыйрьләр Евгений Боратынский, Гавриил Державин, Марина Цветаева һәм Никита Заболоцкий, рәссамнар Иван Шишкин һәм Николай Фешин. Татар шигъриятенең классигы Габдулла Тукай, герой-шагыйрь Муса Җәлил, композиторлар Фәрит Яруллин, Салих Сәйдәшев, Нәҗип Җиһанов, София Гобәйдуллина һәм башка бик күпләр татар мәдәниятенә дан китергән."
]
}
}

View File

@@ -0,0 +1,78 @@
[
{
"id": "1",
"type": "Sights",
"image": "kremlin",
"head": "Kremlin",
"text": "The construction of the fortress continued from the 10th to the 16th century. After Kazan was conquered by Ivan the Terrible in 1552, the Tatar Kremlin was destroyed. On its site, Pskov architects built massive white stone walls, leaving only a few fragments of the old structure. In the 18th century, the Kremlin lost its military significance but remained an administrative and cultural center of the Volga region for a long time."
},
{
"id": "2",
"image": "kulsharif",
"head": "Kul Sharif Mosque",
"text": "This is one of Kazan's landmarks. Moreover, Kul Sharif is also the main Juma Mosque of Tatarstan. Its construction began in 1996 to restore an important architectural relic of the Kazan Khanate, destroyed by Ivan the Terrible's troops in 1552. The mosque was named in honor of the last imam of Kazan, Kul Sharif."
},
{
"id": "3",
"image": "suumbike",
"head": "Suyumbike Tower",
"text": "The structure was first mentioned in documents in 1703, but there is no exact information about its construction date or the origin of its name. According to one version, it was a watchtower because its top provides a good view of the surroundings as well as the Kazanka and Volga rivers."
},
{
"id": "4",
"type": "Active leisure",
"image": "cyrc",
"head": "Kazan Circus",
"text": "One of the striking monuments of Soviet modernism. From afar, the circus building resembles a flying saucer. This 'cosmic' shape was achieved after a major reconstruction in 1967. Avant-garde architectural and engineering solutions were used for its construction."
},
{
"id": "5",
"image": "park",
"head": "URAM Extreme Park",
"text": "URAM is the largest extreme park in Russia, consisting of two parts - open and indoor. The outdoor section, which combines professional extreme zones and walking areas, opened in the summer of 2020 and has become one of the most popular public spaces in Kazan, as well as a place where athletes prepared for world-class competitions, such as the Tokyo Olympics."
},
{
"id": "6",
"image": "zoo",
"head": "Zambezi River Zoo",
"text": "The Zambezi River Zoo in Kazan is one of the oldest zoological gardens in Europe. It offers an exciting journey into the world of animals and plants. This unique place allows visitors to enjoy the richness of flora and fauna. It features diverse exhibits, including animals from various continents, from exotic species to local inhabitants."
},
{
"id": "7",
"type": "Theatres and museums",
"head": "Ekiyat Puppet Theater",
"text": "The Ekiyat Puppet Theater in Kazan represents a unique combination of traditional and contemporary art. It is known for its vibrant performances that attract the attention of both children and adults. Located in the city center, it has become an integral part of the region's cultural life.",
"image": "akiyat"
},
{
"id": "8",
"head": "Opera and Ballet Theater",
"text": "The Opera and Ballet Theater in Kazan is the pinnacle of musical and theatrical art in the region. It allows audiences to enjoy high-class opera performances and magnificent ballet shows that leave unforgettable impressions.",
"image": "opera"
},
{
"id": "9",
"head": "K. Tinchurin Theater",
"text": "The Tinchurin Theater embodies the traditions of classical art, offering audiences a wide range of performances, from dramas and comedies to musicals and ballets. The history of the K. Tinchurin Theater spans decades of art and cultural heritage.",
"image": "tinchurina"
},
{
"id": "10",
"type": "Food and drinks",
"head": "Tubetey",
"text": "Tubetey is a cozy establishment in Kazan offering visitors a wide selection of Tatar cuisine dishes in an atmosphere of hospitality and comfort. Here, you can enjoy Tatar dishes such as chak-chak, kebabs, manti, and more.",
"image": "tubetey"
},
{
"id": "11",
"head": "MORE & MORE",
"text": "This restaurant specializes in seafood and fish. The More & More restaurant is a conceptual project by ALBA GROUP with a focus on seafood and wine. By Kazan standards, the place is expensive, but the dishes and ingredients justify the cost.",
"image": "more"
},
{
"id": "12",
"head": "Paloma Cantina",
"text": "Paloma Cantina is a Mexican cafe. It was opened by the founders of the St. Petersburg bar El Copitas, which was included in the global ranking of The Worlds 50 Best Bars. If you feel lonely in Kazan or want bright colors, this is the place to go.",
"image": "paloma"
}
]

Some files were not shown because too many files have changed in this diff Show More