mongoose + tests

This commit is contained in:
Primakov Alexandr Alexandrovich 2024-10-16 11:06:23 +03:00
parent 2cfcd7347b
commit 4b0d9b4dbc
1295 changed files with 4579 additions and 1719 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],
},
}

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
node_modules/
.env
.idea
coverage/

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,4 +1,4 @@
FROM node:18
FROM node:20
RUN mkdir -p /usr/src/app/server/
WORKDIR /usr/src/app/

6
Jenkinsfile vendored
View File

@ -26,6 +26,12 @@ pipeline {
}
}
stage('archiving') {
script {
archiveArtifacts artifacts: 'coverage/*/**'
}
}
stage('clean-all') {
steps {
sh 'rm -rf .[!.]*'

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\\\\",
"\\\\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: undefined,
// 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;

5179
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,7 +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": "jest",
"test:start": "start-server-and-test up:prod 8044 test"
},
"repository": {
@ -38,6 +38,7 @@
"jsdom": "^22.1.0",
"jsonwebtoken": "^8.5.1",
"mongodb": "^3.6.8",
"mongoose": "^8.7.1",
"mysql": "^2.18.1",
"pbkdf2-password": "^1.2.1",
"socket.io": "^4.7.1",
@ -45,10 +46,13 @@
"uuid": "^9.0.0"
},
"devDependencies": {
"@eslint/js": "^9.12.0",
"@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": "^9.12.0",
"globals": "^15.11.0",
"jest": "^29.7.0",
"mockingoose": "^2.16.2",
"nodemon": "3.0.1",
"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

@ -7,6 +7,8 @@ const app = express()
const cors = require('cors')
require('dotenv').config()
exports.app = app
const config = require('../.serverrc')
const { setIo } = require('./io')
@ -40,35 +42,8 @@ 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('/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('/todo', require('./routers/todo/routes'))
app.use(require('./error'))

View File

@ -1,17 +1,23 @@
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) => {
router.get('/', async (req, res) => {
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 mongoose.modelNames()).map((name) => `<li>${name}</li>`)}</ul>
`)
})

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),
}));
}))
plantsRouter.get('/api/plants', (req, res) => {
res.json(plantsWithDates);
});
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'))

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

@ -1,7 +1,7 @@
const ObjectId = require('mongodb').ObjectID
const getHash = require('pbkdf2-password')()
const { getDB } = require('../../utils/mongo')
const { getDB } = require('../../../utils/mongo')
const USERS_COLLECTION = 'users'
const LISTS_COLLECTION = 'lists'

View File

Before

Width:  |  Height:  |  Size: 377 B

After

Width:  |  Height:  |  Size: 377 B

View File

Before

Width:  |  Height:  |  Size: 470 B

After

Width:  |  Height:  |  Size: 470 B

View File

Before

Width:  |  Height:  |  Size: 578 B

After

Width:  |  Height:  |  Size: 578 B

View File

Before

Width:  |  Height:  |  Size: 481 B

After

Width:  |  Height:  |  Size: 481 B

View File

Before

Width:  |  Height:  |  Size: 368 B

After

Width:  |  Height:  |  Size: 368 B

View File

Before

Width:  |  Height:  |  Size: 593 B

After

Width:  |  Height:  |  Size: 593 B

View File

Before

Width:  |  Height:  |  Size: 539 B

After

Width:  |  Height:  |  Size: 539 B

View File

Before

Width:  |  Height:  |  Size: 414 B

After

Width:  |  Height:  |  Size: 414 B

View File

Before

Width:  |  Height:  |  Size: 414 B

After

Width:  |  Height:  |  Size: 414 B

View File

Before

Width:  |  Height:  |  Size: 739 B

After

Width:  |  Height:  |  Size: 739 B

View File

Before

Width:  |  Height:  |  Size: 686 B

After

Width:  |  Height:  |  Size: 686 B

View File

Before

Width:  |  Height:  |  Size: 750 B

After

Width:  |  Height:  |  Size: 750 B

View File

Before

Width:  |  Height:  |  Size: 687 B

After

Width:  |  Height:  |  Size: 687 B

View File

Before

Width:  |  Height:  |  Size: 706 B

After

Width:  |  Height:  |  Size: 706 B

View File

Before

Width:  |  Height:  |  Size: 776 B

After

Width:  |  Height:  |  Size: 776 B

View File

Before

Width:  |  Height:  |  Size: 628 B

After

Width:  |  Height:  |  Size: 628 B

View File

Before

Width:  |  Height:  |  Size: 742 B

After

Width:  |  Height:  |  Size: 742 B

View File

Before

Width:  |  Height:  |  Size: 853 B

After

Width:  |  Height:  |  Size: 853 B

View File

Before

Width:  |  Height:  |  Size: 911 B

After

Width:  |  Height:  |  Size: 911 B

View File

Before

Width:  |  Height:  |  Size: 601 B

After

Width:  |  Height:  |  Size: 601 B

View File

Before

Width:  |  Height:  |  Size: 648 B

After

Width:  |  Height:  |  Size: 648 B

View File

Before

Width:  |  Height:  |  Size: 709 B

After

Width:  |  Height:  |  Size: 709 B

View File

Before

Width:  |  Height:  |  Size: 442 B

After

Width:  |  Height:  |  Size: 442 B

View File

Before

Width:  |  Height:  |  Size: 858 B

After

Width:  |  Height:  |  Size: 858 B

View File

Before

Width:  |  Height:  |  Size: 718 B

After

Width:  |  Height:  |  Size: 718 B

View File

Before

Width:  |  Height:  |  Size: 1015 B

After

Width:  |  Height:  |  Size: 1015 B

View File

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

Before

Width:  |  Height:  |  Size: 811 B

After

Width:  |  Height:  |  Size: 811 B

View File

Before

Width:  |  Height:  |  Size: 872 B

After

Width:  |  Height:  |  Size: 872 B

View File

Before

Width:  |  Height:  |  Size: 767 B

After

Width:  |  Height:  |  Size: 767 B

View File

Before

Width:  |  Height:  |  Size: 719 B

After

Width:  |  Height:  |  Size: 719 B

View File

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

Before

Width:  |  Height:  |  Size: 812 B

After

Width:  |  Height:  |  Size: 812 B

View File

Before

Width:  |  Height:  |  Size: 760 B

After

Width:  |  Height:  |  Size: 760 B

View File

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

Before

Width:  |  Height:  |  Size: 955 B

After

Width:  |  Height:  |  Size: 955 B

View File

Before

Width:  |  Height:  |  Size: 908 B

After

Width:  |  Height:  |  Size: 908 B

View File

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

View File

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

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