Compare commits
No commits in common. "master" and "connectme-request" have entirely different histories.
master
...
connectme-
165
package-lock.json
generated
165
package-lock.json
generated
@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "multi-stub",
|
||||
"version": "1.2.1",
|
||||
"version": "1.2.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "multi-stub",
|
||||
"version": "1.2.1",
|
||||
"version": "1.2.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ai": "^4.1.13",
|
||||
@ -25,9 +25,7 @@
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"mongodb": "^6.12.0",
|
||||
"mongoose": "^8.9.2",
|
||||
"mongoose-sequence": "^6.0.1",
|
||||
"morgan": "^1.10.0",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"pbkdf2-password": "^1.2.1",
|
||||
"rotating-file-stream": "^3.2.5",
|
||||
"socket.io": "^4.8.1",
|
||||
@ -2085,12 +2083,6 @@
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/append-field": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
|
||||
"integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/aproba": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz",
|
||||
@ -2141,12 +2133,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/async": {
|
||||
"version": "3.2.6",
|
||||
"resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz",
|
||||
"integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/asynckit": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
|
||||
@ -2450,19 +2436,9 @@
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
|
||||
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/busboy": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
|
||||
"integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
|
||||
"dependencies": {
|
||||
"streamsearch": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/bytes": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
||||
@ -2725,21 +2701,6 @@
|
||||
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
|
||||
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="
|
||||
},
|
||||
"node_modules/concat-stream": {
|
||||
"version": "1.6.2",
|
||||
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz",
|
||||
"integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==",
|
||||
"engines": [
|
||||
"node >= 0.8"
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"buffer-from": "^1.0.0",
|
||||
"inherits": "^2.0.3",
|
||||
"readable-stream": "^2.2.2",
|
||||
"typedarray": "^0.0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/console-control-strings": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz",
|
||||
@ -2806,12 +2767,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/core-util-is": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
|
||||
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/cors": {
|
||||
"version": "2.8.5",
|
||||
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
|
||||
@ -4616,12 +4571,6 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/isarray": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
|
||||
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/isexe": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
|
||||
@ -5693,12 +5642,6 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash": {
|
||||
"version": "4.17.21",
|
||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
|
||||
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.includes": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
|
||||
@ -5885,15 +5828,6 @@
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/minimist": {
|
||||
"version": "1.2.8",
|
||||
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
|
||||
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/minipass": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz",
|
||||
@ -6061,19 +5995,6 @@
|
||||
"url": "https://opencollective.com/mongoose"
|
||||
}
|
||||
},
|
||||
"node_modules/mongoose-sequence": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/mongoose-sequence/-/mongoose-sequence-6.0.1.tgz",
|
||||
"integrity": "sha512-uXnLCW9pu2V49Xw8BmdXdeRugd2mv+ntu3nT2Bbm33pNRmmvHE2GKA+8BASKoQt960McLX4VL78wkb492f6MoQ==",
|
||||
"license": "GPL-2.0",
|
||||
"dependencies": {
|
||||
"async": "^3.2.5",
|
||||
"lodash": "^4.17.21"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"mongoose": ">=5"
|
||||
}
|
||||
},
|
||||
"node_modules/mongoose/node_modules/mongodb": {
|
||||
"version": "6.12.0",
|
||||
"resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.12.0.tgz",
|
||||
@ -6203,36 +6124,6 @@
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
|
||||
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
|
||||
},
|
||||
"node_modules/multer": {
|
||||
"version": "1.4.5-lts.1",
|
||||
"resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.1.tgz",
|
||||
"integrity": "sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"append-field": "^1.0.0",
|
||||
"busboy": "^1.0.0",
|
||||
"concat-stream": "^1.5.2",
|
||||
"mkdirp": "^0.5.4",
|
||||
"object-assign": "^4.1.1",
|
||||
"type-is": "^1.6.4",
|
||||
"xtend": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/multer/node_modules/mkdirp": {
|
||||
"version": "0.5.6",
|
||||
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
|
||||
"integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"minimist": "^1.2.6"
|
||||
},
|
||||
"bin": {
|
||||
"mkdirp": "bin/cmd.js"
|
||||
}
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.8",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.8.tgz",
|
||||
@ -6790,12 +6681,6 @@
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/process-nextick-args": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
|
||||
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/prompts": {
|
||||
"version": "2.4.2",
|
||||
"resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz",
|
||||
@ -6923,27 +6808,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/readable-stream": {
|
||||
"version": "2.3.8",
|
||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
|
||||
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"core-util-is": "~1.0.0",
|
||||
"inherits": "~2.0.3",
|
||||
"isarray": "~1.0.0",
|
||||
"process-nextick-args": "~2.0.0",
|
||||
"safe-buffer": "~5.1.1",
|
||||
"string_decoder": "~1.1.1",
|
||||
"util-deprecate": "~1.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/readable-stream/node_modules/safe-buffer": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
|
||||
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/readdirp": {
|
||||
"version": "3.6.0",
|
||||
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
|
||||
@ -7524,14 +7388,6 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/streamsearch": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
|
||||
"integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/string_decoder": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
|
||||
@ -7924,12 +7780,6 @@
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/typedarray": {
|
||||
"version": "0.0.6",
|
||||
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
|
||||
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/uid-safe": {
|
||||
"version": "2.1.5",
|
||||
"resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz",
|
||||
@ -8233,15 +8083,6 @@
|
||||
"resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
|
||||
"integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw=="
|
||||
},
|
||||
"node_modules/xtend": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
||||
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/y18n": {
|
||||
"version": "5.0.8",
|
||||
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
|
||||
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "multi-stub",
|
||||
"version": "1.2.1",
|
||||
"version": "1.2.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
@ -39,9 +39,7 @@
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"mongodb": "^6.12.0",
|
||||
"mongoose": "^8.9.2",
|
||||
"mongoose-sequence": "^6.0.1",
|
||||
"morgan": "^1.10.0",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"pbkdf2-password": "^1.2.1",
|
||||
"rotating-file-stream": "^3.2.5",
|
||||
"socket.io": "^4.8.1",
|
||||
|
@ -1,2 +0,0 @@
|
||||
exports.DSF_AUTH_USER_MODEL_NAME = 'DSF_AUTH_USER'
|
||||
exports.DSF_INTERACTION_MODEL_NAME = 'DSF_INTERACTION'
|
@ -7,29 +7,29 @@ router.get("/users", (request, response) => {
|
||||
router.post("/auth", (request, response) => {
|
||||
const { phoneNumber, password } = request.body;
|
||||
console.log(phoneNumber, password);
|
||||
if (phoneNumber === "89999999999" || phoneNumber === "89559999999") {
|
||||
response.send(require("./json/auth/success.json"));
|
||||
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.status(401).send(require("./json/auth/error.json"));
|
||||
response.send(require("./json/auth/owner.success.json"));
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/auth/2fa", (request, response) => {
|
||||
const { phoneNumber, code } = request.body;
|
||||
if (code === "0000" && phoneNumber === "89999999999") {
|
||||
response.send(require("./json/2fa/dogsitter.success.json"));
|
||||
} else if (code === "0000" && phoneNumber === "89559999999") {
|
||||
response.send(require("./json/2fa/owner.success.json"));
|
||||
const { code } = request.body;
|
||||
if (code === "0000") {
|
||||
response.send(require("./json/2fa/success.json"));
|
||||
} else {
|
||||
response.status(401).send(require("./json/2fa/error.json"));
|
||||
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 === "89999999999" || phoneNumber === "89559999999") {
|
||||
response.status(401).send(require("./json/register/error.json"));
|
||||
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 {
|
||||
@ -37,192 +37,4 @@ router.post("/register", (request, response) => {
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/auth/session", (request, response) => {
|
||||
const authHeader = request.headers.authorization;
|
||||
|
||||
if (!authHeader) {
|
||||
return response.status(401).json({ error: "Authorization header missing" });
|
||||
}
|
||||
|
||||
// Берём сам токен из заголовка
|
||||
const token = authHeader.split(" ")[1];
|
||||
|
||||
if (!token) {
|
||||
return response.status(401).json({ error: "Bearer token missing" });
|
||||
}
|
||||
|
||||
const jwt = require("jsonwebtoken");
|
||||
const secretKey = "secret";
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, secretKey);
|
||||
|
||||
if (decoded.role === "dogsitter") {
|
||||
response.send(require("./json/role/dogsitter.success.json"));
|
||||
} else {
|
||||
response.send(require("./json/role/owner.success.json"));
|
||||
}
|
||||
} catch (e) {
|
||||
console.log("token e:", e);
|
||||
return response.status(403).json({ error: "Invalid token" });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// Проверка взаимодействия между пользователем и догситтером
|
||||
router.get("/interactions/check", (req, res) => {
|
||||
const { owner_id, dogsitter_id } = req.query;
|
||||
|
||||
const usersFilePath = path.resolve(__dirname, "./json/users/users.json");
|
||||
|
||||
delete require.cache[require.resolve(usersFilePath)];
|
||||
const usersFile = require(usersFilePath);
|
||||
|
||||
const interactions = usersFile.interactions || [];
|
||||
|
||||
const exists = interactions.some(
|
||||
(interaction) =>
|
||||
interaction.owner_id === Number(owner_id) &&
|
||||
interaction.dogsitter_id === Number(dogsitter_id)
|
||||
);
|
||||
|
||||
res.json({ exists });
|
||||
});
|
||||
|
||||
// Добавление нового взаимодействия
|
||||
router.post("/interactions", (req, res) => {
|
||||
const { owner_id, dogsitter_id, interaction_type } = req.body;
|
||||
|
||||
if (!owner_id || !dogsitter_id || !interaction_type) {
|
||||
return res.status(400).json({ error: "Missing required fields" });
|
||||
}
|
||||
|
||||
const usersFilePath = path.resolve(__dirname, "./json/users/users.json");
|
||||
|
||||
delete require.cache[require.resolve(usersFilePath)];
|
||||
const usersFile = require(usersFilePath);
|
||||
|
||||
if (!usersFile.interactions) {
|
||||
usersFile.interactions = [];
|
||||
}
|
||||
|
||||
// Проверяем, существует ли уже такое взаимодействие
|
||||
const exists = usersFile.interactions.some(
|
||||
(interaction) =>
|
||||
interaction.owner_id === Number(owner_id) &&
|
||||
interaction.dogsitter_id === Number(dogsitter_id)
|
||||
);
|
||||
|
||||
if (!exists) {
|
||||
usersFile.interactions.push({
|
||||
owner_id: Number(owner_id),
|
||||
dogsitter_id: Number(dogsitter_id),
|
||||
interaction_type,
|
||||
});
|
||||
|
||||
fs.writeFileSync(
|
||||
usersFilePath,
|
||||
JSON.stringify(usersFile, null, 2),
|
||||
"utf8"
|
||||
);
|
||||
|
||||
console.log(
|
||||
`Добавлено взаимодействие: owner_id=${owner_id}, dogsitter_id=${dogsitter_id}`
|
||||
);
|
||||
}
|
||||
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
router.get("/dogsitter-viewing", (req, res) => {
|
||||
const { id } = req.query;
|
||||
console.log(`Получен запрос для dogsitter с ID: ${id}`);
|
||||
|
||||
const usersFile = require("./json/users/users.json");
|
||||
const users = usersFile.data; // Извлекаем массив из свойства "data"
|
||||
|
||||
const user = users.find((user) => user.id === Number(id));
|
||||
|
||||
if (user) {
|
||||
res.json(user); // Возвращаем найденного пользователя
|
||||
} else {
|
||||
res.status(404).json({ error: "User not found" }); // Если пользователь не найден
|
||||
}
|
||||
});
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
|
||||
router.post('/dogsitter-viewing/rating/:id', (req, res) => {
|
||||
const { id } = req.params;
|
||||
const { rating } = req.body;
|
||||
|
||||
if (!rating || rating < 1 || rating > 5) {
|
||||
return res.status(400).json({ error: 'Некорректная оценка' });
|
||||
}
|
||||
|
||||
const usersFilePath = path.resolve(__dirname, "./json/users/users.json");
|
||||
|
||||
delete require.cache[require.resolve(usersFilePath)];
|
||||
const usersFile = require(usersFilePath);
|
||||
const users = usersFile.data;
|
||||
|
||||
const userIndex = users.findIndex(user => user.id === Number(id));
|
||||
if (userIndex === -1) {
|
||||
return res.status(404).json({ error: 'Догситтер не найден' });
|
||||
}
|
||||
|
||||
if (!users[userIndex].ratings) {
|
||||
users[userIndex].ratings = [];
|
||||
}
|
||||
users[userIndex].ratings.push(rating);
|
||||
|
||||
if (users[userIndex].ratings.length > 100) {
|
||||
users[userIndex].ratings.shift();
|
||||
}
|
||||
|
||||
const total = users[userIndex].ratings.reduce((sum, r) => sum + r, 0);
|
||||
users[userIndex].rating = parseFloat((total / users[userIndex].ratings.length).toFixed(2));
|
||||
|
||||
fs.writeFileSync(usersFilePath, JSON.stringify({ data: users }, null, 2), 'utf8');
|
||||
|
||||
console.log(`Обновлен рейтинг догситтера ${id}: ${users[userIndex].rating}`);
|
||||
|
||||
res.json({ rating: users[userIndex].rating, ratings: users[userIndex].ratings });
|
||||
});
|
||||
|
||||
|
||||
router.patch('/users/:id', (req, res) => {
|
||||
const { id } = req.params;
|
||||
const updateData = req.body;
|
||||
|
||||
console.log('Полученные данные для обновления:', updateData);
|
||||
|
||||
|
||||
const usersFilePath = path.resolve(__dirname, "./json/users/users.json");
|
||||
|
||||
delete require.cache[require.resolve(usersFilePath)];
|
||||
const usersFile = require(usersFilePath);
|
||||
const users = usersFile.data;
|
||||
|
||||
const userIndex = users.findIndex((user) => user.id === Number(id));
|
||||
if (userIndex === -1) {
|
||||
return res.status(404).json({ error: 'User not found' });
|
||||
}
|
||||
|
||||
users[userIndex] = { ...users[userIndex], ...updateData };
|
||||
|
||||
fs.writeFileSync(
|
||||
usersFilePath,
|
||||
JSON.stringify({ data: users }, null, 2),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
console.log('Обновлённые данные пользователя:', users[userIndex]);
|
||||
|
||||
res.json(users[userIndex]);
|
||||
});
|
||||
|
||||
|
||||
module.exports = router
|
||||
module.exports = router;
|
||||
|
@ -1,3 +0,0 @@
|
||||
{
|
||||
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwicm9sZSI6ImRvZ3NpdHRlciIsImlhdCI6MTUxNjIzOTAyMn0.7q66wTNyLZp3TGFYF_JdU-yhlWViJulTxP_PCQzO4OI"
|
||||
}
|
@ -1,5 +1,4 @@
|
||||
{
|
||||
"status": "error",
|
||||
"message": "Invalid code",
|
||||
"statusCode": 401
|
||||
"message": "Invalid code."
|
||||
}
|
||||
|
@ -1,3 +0,0 @@
|
||||
{
|
||||
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Mywicm9sZSI6Im93bmVyIiwiaWF0IjoxNTE2MjM5MDIyfQ.sI9839YXveTpEWhdpr5QbCYllt6hHYO7NsrQDcrXZIQ"
|
||||
}
|
4
server/routers/dogsitters-finder/json/2fa/success.json
Normal file
4
server/routers/dogsitters-finder/json/2fa/success.json
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"status": "success",
|
||||
"message": "Two-factor authentication passed."
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
{
|
||||
"data": {
|
||||
"id": 1,
|
||||
"phoneNumber": 89283244141,
|
||||
"firstName": "Вася",
|
||||
"secondName": "Пупкин",
|
||||
"role": "dogsitter",
|
||||
"location": "Россия, республика Татарстан, Казань, улица Пушкина, 12",
|
||||
"price": 1500,
|
||||
"aboutMe": "Я люблю собак"
|
||||
}
|
||||
}
|
@ -1,5 +1,3 @@
|
||||
{
|
||||
"message": "Неверный логин или пароль",
|
||||
"error": "Unauthorized",
|
||||
"statusCode": 401
|
||||
}
|
||||
"error": "Пользователь не найден"
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
{
|
||||
"data": {
|
||||
"id": 3,
|
||||
"phoneNumber": 89872855893,
|
||||
"firstName": "Гадий",
|
||||
"secondName": "Петрович",
|
||||
"role": "owner"
|
||||
}
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
{
|
||||
"status": "success",
|
||||
"message": "Первый фактор аутентификации пройден",
|
||||
"statusCode": 200
|
||||
}
|
@ -1,3 +1,12 @@
|
||||
{
|
||||
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NSwicm9sZSI6ImRvZ3NpdHRlciIsImlhdCI6MTUxNjIzOTAyMn0.T9V3-f3rD1deA5a2J-tYNw0cACEpzKHbhMPkc7gh8c0"
|
||||
"data": {
|
||||
"id": 5,
|
||||
"phoneNumber": 89555555555,
|
||||
"firstName": "Масяня",
|
||||
"secondName": "Карлова",
|
||||
"role": "dogsitter",
|
||||
"location": "Россия, республика Татарстан, Казань, улица Пушкина, 12",
|
||||
"price": 100,
|
||||
"aboutMe": "Все на свете - собаки"
|
||||
}
|
||||
}
|
@ -1,5 +1,3 @@
|
||||
{
|
||||
"message": "Такой пользователь уже был зарегистрирован",
|
||||
"error": "Unauthorized",
|
||||
"statusCode": 401
|
||||
"error": "Пользователь с таким номером телефона уже существует"
|
||||
}
|
@ -1,3 +1,9 @@
|
||||
{
|
||||
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6Niwicm9sZSI6Im93bmVyIiwiaWF0IjoxNTE2MjM5MDIyfQ.qgOhk9tNcaMRbarRWISTgvGx5Eq_X8fcA5lhdVs2tQI"
|
||||
"data": {
|
||||
"id": 6,
|
||||
"phoneNumber": 89888888888,
|
||||
"firstName": "Генадий",
|
||||
"secondName": "Паровозов",
|
||||
"role": "owner"
|
||||
}
|
||||
}
|
@ -1,4 +0,0 @@
|
||||
{
|
||||
"id": 1,
|
||||
"role": "dogsitter"
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
{
|
||||
"message": "Неверный jwt token",
|
||||
"error": "Forbidden",
|
||||
"statusCode": 403
|
||||
}
|
@ -1,4 +0,0 @@
|
||||
{
|
||||
"id": 3,
|
||||
"role": "owner"
|
||||
}
|
@ -1,69 +1,39 @@
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": 1,
|
||||
"phone_number": "89999999999",
|
||||
"first_name": "Вася",
|
||||
"second_name": "Пупкин",
|
||||
"role": "dogsitter",
|
||||
"location": "Россия, республика Татарстан, Казань, Пушкина, 12",
|
||||
"price": "1500",
|
||||
"about_me": "Я люблю собак!",
|
||||
"rating": 5,
|
||||
"ratings": [
|
||||
5,
|
||||
5
|
||||
],
|
||||
"tg": "jullllllie"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"phone_number": 89272844541,
|
||||
"first_name": "Ваня",
|
||||
"second_name": "Пуськин",
|
||||
"role": "dogsitter",
|
||||
"location": "Россия, республика Татарстан, Казань, улица Абсалямова, 19",
|
||||
"price": 2000,
|
||||
"about_me": "Я не люблю собак. И вообще я котоман.",
|
||||
"rating": 4,
|
||||
"ratings": [
|
||||
4,
|
||||
4
|
||||
],
|
||||
"tg": "vanya006"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"phone_number": 89559999999,
|
||||
"first_name": "Гадий",
|
||||
"second_name": "Петрович",
|
||||
"role": "owner"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"phone_number": 89872844591,
|
||||
"first_name": "Галкин",
|
||||
"second_name": "Максим",
|
||||
"role": "dogsitter",
|
||||
"location": "Россия, республика Татарстан, Казань, проспект Ямашева, 83",
|
||||
"price": 1750,
|
||||
"about_me": "Миллион алых роз",
|
||||
"rating": 4.5,
|
||||
"ratings": [
|
||||
4,
|
||||
5
|
||||
],
|
||||
"tg": "maks100500"
|
||||
}
|
||||
],
|
||||
"interactions": [
|
||||
{
|
||||
"owner_id": 3,
|
||||
"dogsitter_id": 4
|
||||
},
|
||||
{
|
||||
"owner_id": 1,
|
||||
"dogsitter_id": 2
|
||||
}
|
||||
]
|
||||
}
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"phone_number": 89283244141,
|
||||
"first_name": "Вася",
|
||||
"second_name": "Пупкин",
|
||||
"role": "dogsitter",
|
||||
"location": "Россия, республика Татарстан, Казань, улица Пушкина, 12",
|
||||
"price": 1500,
|
||||
"about_me": "Я люблю собак"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"phone_number": 89272844541,
|
||||
"first_name": "Ваня",
|
||||
"second_name": "Пуськин",
|
||||
"role": "dogsitter",
|
||||
"location": "Россия, республика Татарстан, Казань, улица Абсалямова, 19",
|
||||
"price": 1000000,
|
||||
"about_me": "Я не люблю собак. И вообще я котоман."
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"phone_number": 89872855893,
|
||||
"first_name": "Гадий",
|
||||
"second_name": "Петрович",
|
||||
"role": "owner"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"phone_number": 89872844591,
|
||||
"first_name": "Галкин",
|
||||
"second_name": "Максим",
|
||||
"role": "dogsitter",
|
||||
"location": "Россия, республика Татарстан, Казань, проспект Ямашева, 83",
|
||||
"price": 1000000,
|
||||
"about_me": "Миллион алых роз"
|
||||
}
|
||||
]
|
||||
|
@ -1,24 +0,0 @@
|
||||
const { Schema, model } = require("mongoose");
|
||||
|
||||
const { DSF_AUTH_USER_MODEL_NAME, DSF_INTERACTION_MODEL_NAME } = require("../../const");
|
||||
|
||||
const interactionSchema = new Schema({
|
||||
owner_id: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: DSF_AUTH_USER_MODEL_NAME,
|
||||
required: true
|
||||
},
|
||||
dogsitter_id: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: DSF_AUTH_USER_MODEL_NAME,
|
||||
required: true
|
||||
},
|
||||
timestamp: {
|
||||
type: Date,
|
||||
default: Date.now
|
||||
}
|
||||
});
|
||||
|
||||
interactionSchema.index({ owner_id: 1, dogsitter_id: 1 });
|
||||
|
||||
module.exports.Interaction = model(DSF_INTERACTION_MODEL_NAME, interactionSchema);
|
@ -1,83 +0,0 @@
|
||||
const { Schema, model } = require("mongoose");
|
||||
|
||||
const { DSF_AUTH_USER_MODEL_NAME } = require("../../const");
|
||||
|
||||
const userSchema = new Schema({
|
||||
phone_number: {
|
||||
type: String,
|
||||
required: true,
|
||||
unique: true,
|
||||
match: /^\+?\d{10,15}$/
|
||||
},
|
||||
first_name: {
|
||||
type: String,
|
||||
required: true,
|
||||
trim: true
|
||||
},
|
||||
second_name: {
|
||||
type: String,
|
||||
required: true,
|
||||
trim: true
|
||||
},
|
||||
role: {
|
||||
type: String,
|
||||
enum: ["dogsitter", "owner"],
|
||||
required: true
|
||||
},
|
||||
location: {
|
||||
type: String,
|
||||
required: function() {
|
||||
return this.role === "dogsitter";
|
||||
}
|
||||
},
|
||||
price: {
|
||||
type: Number,
|
||||
min: 0,
|
||||
required: function() {
|
||||
return this.role === "dogsitter";
|
||||
}
|
||||
},
|
||||
about_me: {
|
||||
type: String,
|
||||
maxlength: 500
|
||||
},
|
||||
rating: {
|
||||
type: Number,
|
||||
min: 0,
|
||||
max: 5,
|
||||
default: 0
|
||||
},
|
||||
ratings: {
|
||||
type: [Number],
|
||||
default: [],
|
||||
validate: {
|
||||
validator: function(arr) {
|
||||
return arr.every(v => v >= 0 && v <= 5);
|
||||
},
|
||||
message: "Рейтинг должен быть в диапазоне от 0 до 5!"
|
||||
}
|
||||
},
|
||||
tg: {
|
||||
type: String,
|
||||
match: /^[a-zA-Z0-9_]{5,32}$/
|
||||
},
|
||||
created: {
|
||||
type: Date,
|
||||
default: Date.now
|
||||
}
|
||||
});
|
||||
|
||||
userSchema.virtual("id").get(function() {
|
||||
return this._id.toHexString();
|
||||
});
|
||||
|
||||
userSchema.set("toJSON", {
|
||||
virtuals: true,
|
||||
versionKey: false,
|
||||
transform: function(doc, ret) {
|
||||
delete ret._id;
|
||||
delete ret.__v;
|
||||
}
|
||||
});
|
||||
|
||||
module.exports.User = model(DSF_AUTH_USER_MODEL_NAME, userSchema);
|
@ -1,149 +0,0 @@
|
||||
const { Router } = require('express')
|
||||
const { expressjwt } = require('express-jwt')
|
||||
|
||||
const { getAnswer } = require('../../utils/common')
|
||||
const { User, Interaction } = require('./model')
|
||||
const { TOKEN_KEY } = require('./const')
|
||||
const { requiredValidate } = require('./utils')
|
||||
|
||||
const router = Router()
|
||||
|
||||
// Получение списка пользователей
|
||||
router.get('/users', async (req, res) => {
|
||||
|
||||
const users = await User.find()
|
||||
.select('-__v -ratings -phone_number')
|
||||
.lean()
|
||||
|
||||
console.log('get users successfull')
|
||||
|
||||
res.send(getAnswer(null, users))
|
||||
})
|
||||
|
||||
// Получение конкретного пользователя
|
||||
router.get('/dogsitter-viewing', async (req, res) => {
|
||||
const { userId } = req.params
|
||||
|
||||
const user = await User.findById(userId)
|
||||
.select('-__v -ratings')
|
||||
.lean()
|
||||
|
||||
if (!user) {
|
||||
return res.status(404).send(getAnswer(new Error('Пользователь не найден')))
|
||||
}
|
||||
|
||||
res.send(getAnswer(null, user))
|
||||
})
|
||||
|
||||
router.use(expressjwt({ secret: TOKEN_KEY, algorithms: ['HS256'] }))
|
||||
|
||||
// Добавление оценки пользователю
|
||||
router.post('/dogsitter-viewing/rating', requiredValidate('value'), async (req, res) => {
|
||||
const { userId } = req.params
|
||||
const { value } = req.body
|
||||
const authUserId = req.auth.id
|
||||
|
||||
try {
|
||||
const user = await User.findById(userId)
|
||||
if (!user) throw new Error('Пользователь не найден')
|
||||
if (user.role !== 'dogsitter') throw new Error('Нельзя оценивать этого пользователя')
|
||||
if (user.id === authUserId) throw new Error('Нельзя оценивать самого себя')
|
||||
|
||||
user.ratings.push(Number(value))
|
||||
user.rating = user.ratings.reduce((a, b) => a + b, 0) / user.ratings.length
|
||||
|
||||
const updatedUser = await user.save()
|
||||
|
||||
res.send(getAnswer(null, {
|
||||
id: updatedUser.id,
|
||||
rating: updatedUser.rating.toFixed(1),
|
||||
totalRatings: updatedUser.ratings.length
|
||||
}))
|
||||
|
||||
} catch (error) {
|
||||
res.status(400).send(getAnswer(error))
|
||||
}
|
||||
})
|
||||
|
||||
// Обновление информации пользователя
|
||||
router.patch('/users', async (req, res) => {
|
||||
const { userId } = req.params
|
||||
const updates = req.body
|
||||
|
||||
try {
|
||||
const user = await User.findByIdAndUpdate(userId, updates, { new: true })
|
||||
.select('-__v -ratings')
|
||||
|
||||
if (!user) throw new Error('Пользователь не найден')
|
||||
res.send(getAnswer(null, user))
|
||||
|
||||
} catch (error) {
|
||||
res.status(400).send(getAnswer(error))
|
||||
}
|
||||
})
|
||||
|
||||
// Создание объекта взаимодействия
|
||||
router.post('/interactions',
|
||||
expressjwt({ secret: TOKEN_KEY, algorithms: ['HS256'] }),
|
||||
requiredValidate('dogsitter_id'),
|
||||
async (req, res) => {
|
||||
try {
|
||||
const { dogsitter_id } = req.body
|
||||
const owner_id = req.auth.id // ID из JWT токена
|
||||
|
||||
// Проверка существования пользователей
|
||||
const [owner, dogsitter] = await Promise.all([
|
||||
User.findById(owner_id),
|
||||
User.findById(dogsitter_id)
|
||||
])
|
||||
|
||||
if (!owner || owner.role !== 'owner') {
|
||||
throw new Error('Владелец не найден или имеет неверную роль')
|
||||
}
|
||||
|
||||
if (!dogsitter || dogsitter.role !== 'dogsitter') {
|
||||
throw new Error('Догситтер не найден или имеет неверную роль')
|
||||
}
|
||||
|
||||
// Создание взаимодействия
|
||||
const interaction = await Interaction.create({
|
||||
owner_id,
|
||||
dogsitter_id
|
||||
})
|
||||
|
||||
res.send(getAnswer(null, {
|
||||
id: interaction.id,
|
||||
timestamp: interaction.timestamp
|
||||
}))
|
||||
|
||||
} catch (error) {
|
||||
res.status(400).send(getAnswer(error))
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
router.get('/interactions/check', async (req, res) => {
|
||||
const { owner_id, dogsitter_id } = req.query;
|
||||
|
||||
if (!owner_id || !dogsitter_id) {
|
||||
return res.status(400).send(getAnswer('Missing owner_id or dogsitter_id'));
|
||||
}
|
||||
|
||||
try {
|
||||
// Поиск взаимодействий по owner_id и dogsitter_id
|
||||
const interactions = await Interaction.find({ owner_id, dogsitter_id })
|
||||
.select('-__v') // Выбираем только нужные поля
|
||||
.lean();
|
||||
|
||||
if (interactions.length === 0) {
|
||||
return res.status(404).send(getAnswer('No interactions found'));
|
||||
}
|
||||
|
||||
res.send(getAnswer(null, interactions));
|
||||
} catch (error) {
|
||||
console.error('Error checking interactions:', error);
|
||||
res.status(500).send(getAnswer('Internal Server Error'));
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router
|
@ -1,9 +0,0 @@
|
||||
const getGigaToken = async () => {
|
||||
const response = await fetch('https://admin.bro-js.ru/api/config/v1/dev')
|
||||
const data = await response.json()
|
||||
return data.features['dry-wash-bh'].GIGA_TOKEN.value
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getGigaToken
|
||||
}
|
@ -1,29 +0,0 @@
|
||||
const { Schema, model } = require('mongoose')
|
||||
|
||||
const schema = new Schema({
|
||||
image: String,
|
||||
imageRating: String,
|
||||
imageDescription: String,
|
||||
orderId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: 'dry-wash-order'
|
||||
},
|
||||
created: {
|
||||
type: Date,
|
||||
default: () => new Date().toISOString(),
|
||||
},
|
||||
})
|
||||
|
||||
schema.set('toJSON', {
|
||||
virtuals: true,
|
||||
versionKey: false,
|
||||
transform(_doc, ret) {
|
||||
delete ret._id
|
||||
}
|
||||
})
|
||||
|
||||
schema.virtual('id').get(function () {
|
||||
return this._id.toHexString()
|
||||
})
|
||||
|
||||
exports.OrderCarImgModel = model('dry-wash-order-car-image', schema)
|
@ -1,6 +1,5 @@
|
||||
const { Schema, model } = require('mongoose')
|
||||
const { orderStatus } = require('./const')
|
||||
const { OrderNumberModel } = require('./order.number')
|
||||
|
||||
const schema = new Schema({
|
||||
phone: {
|
||||
@ -28,10 +27,6 @@ const schema = new Schema({
|
||||
type: String,
|
||||
required: true
|
||||
},
|
||||
orderNumber: {
|
||||
type: String,
|
||||
unique: true
|
||||
},
|
||||
status: {
|
||||
type: String,
|
||||
required: true,
|
||||
@ -52,18 +47,6 @@ const schema = new Schema({
|
||||
},
|
||||
})
|
||||
|
||||
schema.pre('save', async function (next) {
|
||||
if (this.isNew) {
|
||||
const counter = await OrderNumberModel.findOneAndUpdate(
|
||||
{ _id: 'orderNumber' },
|
||||
{ $inc: { sequenceValue: 1 } },
|
||||
{ new: true, upsert: true }
|
||||
)
|
||||
this.orderNumber = counter.sequenceValue.toString()
|
||||
}
|
||||
next()
|
||||
})
|
||||
|
||||
schema.set('toJSON', {
|
||||
virtuals: true,
|
||||
versionKey: false,
|
||||
|
@ -1,14 +0,0 @@
|
||||
const { Schema, model } = require('mongoose')
|
||||
|
||||
const schema = new Schema({
|
||||
_id: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
sequenceValue: {
|
||||
type: Number,
|
||||
default: 0
|
||||
}
|
||||
})
|
||||
|
||||
exports.OrderNumberModel = model('dry-wash-order-number', schema)
|
@ -1,11 +1,8 @@
|
||||
const mongoose = require("mongoose")
|
||||
const router = require('express').Router()
|
||||
const multer = require('multer')
|
||||
const { MasterModel } = require('./model/master')
|
||||
const { OrderModel } = require('./model/order')
|
||||
const { OrderCarImgModel } = require('./model/order.car-img')
|
||||
const { orderStatus } = require('./model/const')
|
||||
const { getGigaToken } = require('./get-token')
|
||||
|
||||
const isValidPhoneNumber = (value) => /^(\+)?\d{9,15}/.test(value)
|
||||
const isValidCarNumber = (value) => /^[авекмнорстух][0-9]{3}[авекмнорстух]{2}[0-9]{2,3}$/i.test(value)
|
||||
@ -29,9 +26,6 @@ const isValidLocation = (value) => {
|
||||
const isValidOrderStatus = (value) => Object.values(orderStatus).includes(value)
|
||||
const isValidOrderNotes = (value) => value.length < 500
|
||||
|
||||
const allowedMimeTypes = ['image/jpeg', 'image/png']
|
||||
const sizeLimitInMegaBytes = 15
|
||||
|
||||
const VALIDATION_MESSAGES = {
|
||||
order: {
|
||||
notFound: 'Order not found'
|
||||
@ -66,13 +60,6 @@ const VALIDATION_MESSAGES = {
|
||||
carColor: {
|
||||
invalid: 'Invalid car color'
|
||||
},
|
||||
carImg: {
|
||||
required: 'Car image file is required',
|
||||
invalid: {
|
||||
type: `Invalid car image file type. Allowed types: ${allowedMimeTypes}`,
|
||||
size: `Invalid car image file size. Limit is ${sizeLimitInMegaBytes}MB`
|
||||
}
|
||||
},
|
||||
washingBegin: {
|
||||
required: 'Begin time of washing is required',
|
||||
invalid: 'Invalid begin time of washing'
|
||||
@ -156,21 +143,17 @@ router.post('/create', async (req, res, next) => {
|
||||
|
||||
router.get('/:id', async (req, res, next) => {
|
||||
const { id } = req.params
|
||||
|
||||
if (!mongoose.Types.ObjectId.isValid(id)) {
|
||||
throw new Error(VALIDATION_MESSAGES.orderId.invalid)
|
||||
}
|
||||
|
||||
try {
|
||||
const order = await OrderModel.findById(id)
|
||||
|
||||
if (!order) {
|
||||
throw new Error(VALIDATION_MESSAGES.order.notFound)
|
||||
}
|
||||
|
||||
const imgProps = await OrderCarImgModel.findOne({ orderId: order.id })
|
||||
|
||||
res.status(200).send({ success: true, body: { ...order.toObject(), ...imgProps?.toObject() } })
|
||||
res.status(200).send({ success: true, body: order })
|
||||
} catch (error) {
|
||||
next(error)
|
||||
}
|
||||
@ -265,183 +248,4 @@ router.delete('/:id', async (req, res, next) => {
|
||||
}
|
||||
})
|
||||
|
||||
const storage = multer.memoryStorage()
|
||||
const upload = multer({
|
||||
storage: storage,
|
||||
limits: { fileSize: sizeLimitInMegaBytes * 1024 * 1024 },
|
||||
fileFilter: (req, file, cb) => {
|
||||
if (allowedMimeTypes.includes(file.mimetype)) {
|
||||
cb(null, true)
|
||||
} else {
|
||||
cb(new Error(VALIDATION_MESSAGES.carImg.invalid.type), false)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const { v4: uuidv4 } = require("uuid")
|
||||
const axios = require('axios')
|
||||
|
||||
const GIGA_CHAT_OAUTH = 'https://ngw.devices.sberbank.ru:9443/api/v2/oauth'
|
||||
const GIGA_CHAT_API = 'https://gigachat.devices.sberbank.ru/api/v1'
|
||||
|
||||
const getToken = async (req, res) => {
|
||||
const gigaToken = await getGigaToken()
|
||||
|
||||
const rqUID = uuidv4()
|
||||
const body = new URLSearchParams({
|
||||
scope: "GIGACHAT_API_PERS",
|
||||
})
|
||||
|
||||
const response = await fetch(GIGA_CHAT_OAUTH, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Basic ${gigaToken}`,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
Accept: "application/json",
|
||||
RqUID: rqUID,
|
||||
},
|
||||
body,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json()
|
||||
console.error("Ошибка запроса: ", errorData)
|
||||
return res.status(response.status).json(errorData)
|
||||
}
|
||||
|
||||
return await response.json()
|
||||
}
|
||||
|
||||
const uploadImage = async (file, accessToken) => {
|
||||
const formData = new FormData()
|
||||
const blob = new Blob([file.buffer], { type: file.mimetype })
|
||||
formData.append('file', blob, file.originalname)
|
||||
formData.append('purpose', 'general')
|
||||
|
||||
const config = {
|
||||
maxBodyLength: Infinity,
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
'Accept': 'application/json',
|
||||
'Authorization': `Bearer ${accessToken}`
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await axios.post(`${GIGA_CHAT_API}/files`, formData, config)
|
||||
return response.data.id
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
const analyzeImage = async (fileId, token) => {
|
||||
const response = await fetch(`${GIGA_CHAT_API}/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: "GigaChat-Max",
|
||||
stream: false,
|
||||
update_interval: 0,
|
||||
messages: [
|
||||
{
|
||||
role: "system",
|
||||
content:
|
||||
`Ты эксперт по оценке степени загрязнения автомобилей. Твоя задача — анализировать фотографии машин и определять степень их загрязнения.
|
||||
ВАЖНО: Твой ответ ДОЛЖЕН быть СТРОГО в формате JSON и содержать ТОЛЬКО следующие поля:
|
||||
{
|
||||
"value": число от 0 до 10 (целое или с одним знаком после запятой),
|
||||
"description": "текстовое описание на русском языке"
|
||||
}
|
||||
Правила:
|
||||
1. Поле "value":
|
||||
- Должно быть числом от 0 до 10
|
||||
- 0 = машина абсолютно чистая
|
||||
- 10 = машина максимально грязная
|
||||
2. Поле "description":
|
||||
- Должно содержать 2-3 предложения на русском языке
|
||||
- Обязательно указать конкретные признаки загрязнения
|
||||
- Объяснить почему выставлен именно такой балл
|
||||
НЕ ДОБАВЛЯЙ никаких дополнительных полей или комментариев вне JSON структуры.
|
||||
НЕ ИСПОЛЬЗУЙ markdown форматирование.
|
||||
ОТВЕТ ДОЛЖЕН БЫТЬ ВАЛИДНЫМ JSON.`,
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
content: 'Дай оценку для приложенного файла изображения согласно структуре, ответ должен быть на русском языке',
|
||||
attachments: [fileId],
|
||||
},
|
||||
],
|
||||
}),
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
try {
|
||||
return JSON.parse(data.choices[0].message.content)
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
return { description: data.choices[0].message.content }
|
||||
}
|
||||
}
|
||||
|
||||
const convertFileToBase64 = (file) => {
|
||||
const base64Image = file.buffer.toString('base64')
|
||||
return `data:${file.mimetype};base64,${base64Image}`
|
||||
}
|
||||
|
||||
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = "0"
|
||||
|
||||
router.post('/:id/upload-car-img', upload.single('file'), async (req, res) => {
|
||||
const { id: orderId } = req.params
|
||||
if (!mongoose.Types.ObjectId.isValid(orderId)) {
|
||||
throw new Error(VALIDATION_MESSAGES.orderId.invalid)
|
||||
}
|
||||
const order = await OrderModel.findById(orderId)
|
||||
if (!order) {
|
||||
throw new Error(VALIDATION_MESSAGES.order.notFound)
|
||||
}
|
||||
|
||||
if (!req.file) {
|
||||
throw new Error(VALIDATION_MESSAGES.carImg.required)
|
||||
}
|
||||
|
||||
try {
|
||||
await OrderCarImgModel.deleteMany({ orderId })
|
||||
|
||||
const { access_token } = await getToken(req, res)
|
||||
|
||||
const fileId = await uploadImage(req.file, access_token)
|
||||
const { value, description } = await analyzeImage(fileId, access_token) ?? {}
|
||||
|
||||
const orderCarImg = await OrderCarImgModel.create({
|
||||
image: convertFileToBase64(req.file),
|
||||
imageRating: value,
|
||||
imageDescription: description,
|
||||
orderId: order.id,
|
||||
created: new Date().toISOString(),
|
||||
})
|
||||
|
||||
res.status(200).send({ success: true, body: orderCarImg })
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
})
|
||||
|
||||
router.use((err, req, res, next) => {
|
||||
if (err instanceof multer.MulterError) {
|
||||
switch (err.message) {
|
||||
case 'File too large':
|
||||
return res.status(400).json({ success: false, error: VALIDATION_MESSAGES.carImg.invalid.size })
|
||||
default:
|
||||
return res.status(400).json({ success: false, error: err.message })
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(err.message)
|
||||
})
|
||||
|
||||
module.exports = router
|
||||
module.exports = router
|
@ -8,44 +8,22 @@ router.get("/update-like", (request, response) => {
|
||||
response.send(require("./json/gamepage/success.json"));
|
||||
});
|
||||
|
||||
router.get("/add-to-cart", (request, response) => {
|
||||
response.send(require("./json/home-page-data/games-in-cart.json"));
|
||||
});
|
||||
|
||||
router.get("/categories", (request, response) => {
|
||||
response.send(require("./json/home-page-data/all-games.json"));
|
||||
response.send(require("./json/categories/success.json"));
|
||||
});
|
||||
|
||||
router.get("/favourites", (request, response) => {
|
||||
response.send(require("./json/home-page-data/all-games.json"));
|
||||
});
|
||||
|
||||
// router.get("/shopping-cart", (request, response) => {
|
||||
// response.send(require("./json/shopping-cart/success.json"));
|
||||
// });
|
||||
|
||||
router.get("/shopping-cart", (request, response) => {
|
||||
response.send(require("./json/home-page-data/games-in-cart.json"));
|
||||
response.send(require("./json/shopping-cart/success.json"));
|
||||
});
|
||||
|
||||
// Добавляем поддержку разных ответов для /home
|
||||
router.get("/home", (req, res) => {
|
||||
if (stubs.home === "success") {
|
||||
res.send(require("./json/home-page-data/success.json"));
|
||||
} else if (stubs.home === "empty") {
|
||||
res.send({ data: [] }); // Отправляем пустой массив
|
||||
} else {
|
||||
res.status(500).json({ success: false, message: "Server error" });
|
||||
}
|
||||
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"));
|
||||
});
|
||||
|
||||
const stubs = {
|
||||
home: "success",
|
||||
};
|
||||
|
||||
// // Маршрут для обновления лайков
|
||||
// router.post("/update-like", (request, response) => {
|
||||
@ -60,6 +38,7 @@ const stubs = {
|
||||
// });
|
||||
// });
|
||||
|
||||
|
||||
const fs = require("fs").promises;
|
||||
const path = require("path");
|
||||
|
||||
@ -70,7 +49,7 @@ const commentsFilePath = path.join(__dirname, "./json/gamepage/success.json");
|
||||
async function readComments() {
|
||||
const data = await fs.readFile(commentsFilePath, "utf-8");
|
||||
const parsedData = JSON.parse(data);
|
||||
console.log("Прочитанные данные:", parsedData); // Логируем полученные данные
|
||||
console.log("Прочитанные данные:", parsedData); // Логируем полученные данные
|
||||
return parsedData;
|
||||
}
|
||||
// Write to JSON file
|
||||
@ -109,149 +88,5 @@ router.post("/update-like", async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Путь к JSON-файлу с корзиной
|
||||
const cartFilePath = path.join(
|
||||
__dirname,
|
||||
"./json/home-page-data/games-in-cart.json"
|
||||
);
|
||||
|
||||
// Функция для чтения JSON-файла
|
||||
async function readCart() {
|
||||
const data = await fs.readFile(cartFilePath, "utf-8");
|
||||
return JSON.parse(data);
|
||||
}
|
||||
|
||||
// Функция для записи в JSON-файл
|
||||
async function writeCart(data) {
|
||||
await fs.writeFile(cartFilePath, JSON.stringify(data, null, 2), "utf-8");
|
||||
}
|
||||
|
||||
// Маршрут для добавления/удаления товара в корзине
|
||||
router.post("/add-to-cart", async (req, res) => {
|
||||
const { id, action } = req.body;
|
||||
|
||||
// Проверка наличия id и action
|
||||
if (id === undefined || action === undefined) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ success: false, message: "Invalid id or action" });
|
||||
}
|
||||
|
||||
try {
|
||||
const cartData = await readCart();
|
||||
let ids = cartData.data.ids;
|
||||
|
||||
if (action === "add") {
|
||||
// Если action "add", добавляем товар, если его нет в корзине
|
||||
if (!ids?.includes(id)) {
|
||||
ids.push(id);
|
||||
}
|
||||
} else if (action === "remove") {
|
||||
// Если action "remove", удаляем товар, если он есть в корзине
|
||||
if (ids?.includes(id)) {
|
||||
ids = ids.filter((item) => item !== id);
|
||||
}
|
||||
} else {
|
||||
// Если action невалиден
|
||||
return res
|
||||
.status(400)
|
||||
.json({ success: false, message: "Invalid action" });
|
||||
}
|
||||
|
||||
// Записываем обновленные данные обратно в файл
|
||||
cartData.data.ids = ids;
|
||||
await writeCart(cartData);
|
||||
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
message: "Cart updated successfully",
|
||||
data: cartData.data, // Возвращаем обновленные данные
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error updating cart:", error);
|
||||
res.status(500).json({ success: false, message: "Server error" });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
const createElement = (key, value, buttonTitle, basePath) => `
|
||||
<label>
|
||||
<input name="${key}" type="radio" ${
|
||||
stubs[key] === value ? "checked" : ""
|
||||
} onclick="fetch('${basePath}/admin/set/${key}/${value}')"/>
|
||||
${buttonTitle || value}
|
||||
</label>
|
||||
`;
|
||||
|
||||
router.get("/admin/home", (request, response) => {
|
||||
const basePath = request.baseUrl; // Получаем базовый путь маршрутизатора
|
||||
response.send(`
|
||||
<div>
|
||||
<fieldset>
|
||||
<legend>Настройка данных для /home</legend>
|
||||
${createElement("home", "success", "Отдать успешный ответ", basePath)}
|
||||
${createElement("home", "empty", "Отдать пустой массив", basePath)}
|
||||
${createElement("home", "error", "Отдать ошибку", basePath)}
|
||||
</fieldset>
|
||||
</div>
|
||||
`);
|
||||
});
|
||||
|
||||
router.get("/admin/game-page", (request, response) => {
|
||||
response.send(`
|
||||
<div>
|
||||
<fieldset>
|
||||
<legend>Настройка данных для /game-page</legend>
|
||||
${createElement(
|
||||
"game-page",
|
||||
"success",
|
||||
"Отдать успешный ответ"
|
||||
)}
|
||||
${createElement("game-page", "empty", "Отдать пустой массив")}
|
||||
${createElement("game-page", "error", "Отдать ошибку")}
|
||||
|
||||
</fieldset>
|
||||
</div>
|
||||
`);
|
||||
});
|
||||
|
||||
router.get("/admin/categories", (request, response) => {
|
||||
response.send(`
|
||||
<div>
|
||||
<fieldset>
|
||||
<legend>Настройка данных для /categories</legend>
|
||||
${createElement(
|
||||
"categories",
|
||||
"success",
|
||||
"Отдать успешный ответ"
|
||||
)}
|
||||
${createElement("categories", "empty", "Отдать пустой массив")}
|
||||
${createElement("categories", "error", "Отдать ошибку")}
|
||||
</fieldset>
|
||||
</div>
|
||||
`);
|
||||
});
|
||||
|
||||
router.get("/admin/favourites", (request, response) => {
|
||||
response.send(`
|
||||
<div>
|
||||
<fieldset>
|
||||
<legend>Настройка данных для /favourites</legend>
|
||||
${createElement(
|
||||
"favourites",
|
||||
"success",
|
||||
"Отдать успешный ответ"
|
||||
)}
|
||||
${createElement("favourites", "empty", "Отдать пустой массив")}
|
||||
${createElement("favourites", "error", "Отдать ошибку")}
|
||||
</fieldset>
|
||||
</div>
|
||||
`);
|
||||
});
|
||||
|
||||
router.get("/admin/set/:key/:value", (request, response) => {
|
||||
const { key, value } = request.params;
|
||||
stubs[key] = value;
|
||||
response.send("Настройки обновлены!");
|
||||
});
|
@ -0,0 +1,186 @@
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
"games1": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "How to Survive",
|
||||
"price": 259,
|
||||
"old_price": 500,
|
||||
"image": "sales_game1",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "Red Solstice 2 Survivors",
|
||||
"price": 561,
|
||||
"image": "sales_game2",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "Sons Of The Forests",
|
||||
"price": 820,
|
||||
"old_price": 1100,
|
||||
"image": "new_game2",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"title": "The Witcher 3: Wild Hunt",
|
||||
"price": 990,
|
||||
"old_price": 1200,
|
||||
"image": "leaders_game4",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"title": "Atomic Heart",
|
||||
"price": 1200,
|
||||
"old_price": 2500,
|
||||
"image": "leaders_game5",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"title": "Crab Game",
|
||||
"price": 600,
|
||||
"old_price": 890,
|
||||
"image": "leaders_game6",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
}
|
||||
],
|
||||
"games2": [
|
||||
{
|
||||
"id": 7,
|
||||
"title": "Alpha League",
|
||||
"price": 299,
|
||||
"image": "new_game1",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"title": "Sons Of The Forests",
|
||||
"price": 820,
|
||||
"old_price": 1100,
|
||||
"image": "new_game2",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"title": "Pacific Drives",
|
||||
"price": 1799,
|
||||
"image": "new_game3",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"title": "The Witcher 3: Wild Hunt",
|
||||
"price": 990,
|
||||
"old_price": 1200,
|
||||
"image": "leaders_game4",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"title": "Atomic Heart",
|
||||
"price": 1200,
|
||||
"old_price": 2500,
|
||||
"image": "leaders_game5",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"title": "Crab Game",
|
||||
"price": 600,
|
||||
"old_price": 890,
|
||||
"image": "leaders_game6",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
}
|
||||
],
|
||||
"games3": [
|
||||
{
|
||||
"id": 10,
|
||||
"title": "Elden Ring",
|
||||
"price": 3295,
|
||||
"old_price": 3599,
|
||||
"image": "leaders_game2",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"title": "Counter-Strike 2",
|
||||
"price": 479,
|
||||
"image": "leaders_game1",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"title": "PUBG: BATTLEGROUNDS",
|
||||
"price": 199,
|
||||
"image": "leaders_game3",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"title": "The Witcher 3: Wild Hunt",
|
||||
"price": 990,
|
||||
"old_price": 1200,
|
||||
"image": "leaders_game4",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"title": "Atomic Heart",
|
||||
"price": 1200,
|
||||
"old_price": 2500,
|
||||
"image": "leaders_game5",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"title": "Crab Game",
|
||||
"price": 600,
|
||||
"old_price": 890,
|
||||
"image": "leaders_game6",
|
||||
"os": "windows",
|
||||
"fav1": "star1",
|
||||
"fav2": "star2"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
@ -5,28 +5,28 @@
|
||||
{
|
||||
"username": "Пользователь1",
|
||||
"text": "Текст комментария 1",
|
||||
"likes": 13,
|
||||
"likes": 9,
|
||||
"rating": 8,
|
||||
"date": "2025-03-01T10:00:00Z"
|
||||
},
|
||||
{
|
||||
"username": "Пользователь2",
|
||||
"text": "Текст комментария 2",
|
||||
"likes": 10,
|
||||
"likes": 7,
|
||||
"rating": 7,
|
||||
"date": "2025-01-01T10:00:00Z"
|
||||
},
|
||||
{
|
||||
"username": "Пользователь3",
|
||||
"text": "Текст комментария 3",
|
||||
"likes": 4,
|
||||
"likes": 5,
|
||||
"rating": 3,
|
||||
"date": "2025-02-01T10:00:00Z"
|
||||
},
|
||||
{
|
||||
"username": "Пользователь4",
|
||||
"text": "Текст комментария 4",
|
||||
"likes": 18,
|
||||
"likes": 15,
|
||||
"rating": 2,
|
||||
"date": "2025-12-01T10:00:00Z"
|
||||
}
|
||||
|
@ -3,186 +3,147 @@
|
||||
"data": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Elden Ring",
|
||||
"image": "game17",
|
||||
"price": 3295,
|
||||
"old_price": 3599,
|
||||
"imgPath": "img_top_17",
|
||||
"description": "Крупномасштабная RPG, действие которой происходит в обширном открытом мире c богатой мифологией и множеством опасных врагов.",
|
||||
"name": "The Witcher 3: Wild Hunt",
|
||||
"image": "game1",
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_1",
|
||||
"description": "Эпическая RPG с открытым миром, в которой Геральт из Ривии охотится на монстров и раскрывает политические заговоры.",
|
||||
"category": "RPG"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "The Witcher 3: Wild Hunt",
|
||||
"image": "game1",
|
||||
"price": 990,
|
||||
"old_price": 1200,
|
||||
"imgPath": "img_top_1",
|
||||
"description": "Эпическая RPG с открытым миром, в которой Геральт из Ривии охотится на монстров и раскрывает политические заговоры.",
|
||||
"category": "RPG"
|
||||
|
||||
},
|
||||
{
|
||||
"id": 17,
|
||||
"title": "Red Dead Redemption 2",
|
||||
"name": "Red Dead Redemption 2",
|
||||
"image": "game2",
|
||||
"price": 980,
|
||||
"old_price": 3800,
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_2",
|
||||
"description": "Приключенческая игра с открытым миром на Диком Западе, рассказывающая историю Артура Моргана.",
|
||||
"category": "Adventures"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "Forza Horizon 5",
|
||||
"name": "Forza Horizon 5",
|
||||
"image": "game3",
|
||||
"price": 1900,
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_3",
|
||||
"description": "Гоночная игра с огромным открытым миром, действие которой происходит в Мексике.",
|
||||
"category": "Race"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"title": "Atomic Heart",
|
||||
"name": "Atomic Heart",
|
||||
"image": "game4",
|
||||
"price": 1200,
|
||||
"old_price": 2500,
|
||||
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_4",
|
||||
"description": "Экшен-шутер с элементами RPG, разворачивающийся в альтернативной Советской России.",
|
||||
"category": "Shooters"
|
||||
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"title": "Counter-Strike 2",
|
||||
"name": "Counter-Strike 2",
|
||||
"image": "game5",
|
||||
"price": 479,
|
||||
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_5",
|
||||
"description": "Популярный онлайн-шутер с соревновательным геймплеем и тактическими элементами.",
|
||||
"category": "Shooters"
|
||||
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"title": "Grand Theft Auto V",
|
||||
"name": "Grand Theft Auto V",
|
||||
"image": "game6",
|
||||
"price": 700,
|
||||
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_6",
|
||||
"description": "Игра с открытым миром, где можно погрузиться в криминальный мир Лос-Сантоса.",
|
||||
"category": "Adventures"
|
||||
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"title": "Assassin’s Creed IV: Black Flag",
|
||||
"name": "Assassin’s Creed IV: Black Flag",
|
||||
"image": "game7",
|
||||
"price": 1100,
|
||||
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_7",
|
||||
"description": "Приключенческая игра о пиратах и морских сражениях в эпоху золотого века пиратства.",
|
||||
"category": "Adventures"
|
||||
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"title": "Spider-Man",
|
||||
"name": "Spider-Man",
|
||||
"image": "game8",
|
||||
"price": 3800,
|
||||
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_8",
|
||||
"description": "Игра о супергерое Человеке-пауке с захватывающими битвами и паркуром по Нью-Йорку.",
|
||||
"category": "Action"
|
||||
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"title": "Assassin’s Creed Mirage",
|
||||
"name": "Assassin’s Creed Mirage",
|
||||
"image": "game9",
|
||||
"price": 1600,
|
||||
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_9",
|
||||
"description": "Приключенческая игра с упором на скрытность, вдохновленная классическими частями серии.",
|
||||
"category": "Action"
|
||||
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"title": "Assassin’s Creed Valhalla",
|
||||
"name": "Assassin’s Creed Valhalla",
|
||||
"image": "game10",
|
||||
"price": 800,
|
||||
"old_price": 2200,
|
||||
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_10",
|
||||
"description": "RPG с открытым миром о викингах, включающая битвы, исследования и строительство поселений.",
|
||||
"category": "RPG"
|
||||
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"title": "ARK: Survival Evolved",
|
||||
"name": "ARK: Survival Evolved",
|
||||
"image": "game11",
|
||||
"price": 790,
|
||||
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_11",
|
||||
"description": "Выживание в открытом мире с динозаврами, строительством и многопользовательскими элементами.",
|
||||
"category": "Simulators"
|
||||
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"title": "FIFA 23",
|
||||
"name": "FIFA 23",
|
||||
"image": "game12",
|
||||
"price": 3900,
|
||||
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_12",
|
||||
"description": "Популярный футбольный симулятор с улучшенной графикой и реалистичным геймплеем.",
|
||||
"category": "Sports"
|
||||
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"title": "Dirt 5",
|
||||
"name": "Dirt 5",
|
||||
"image": "game13",
|
||||
"price": 2300,
|
||||
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_13",
|
||||
"description": "Аркадная гоночная игра с фокусом на ралли и внедорожных соревнованиях.",
|
||||
"category": "Race"
|
||||
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"title": "Cyberpunk 2077",
|
||||
"name": "Cyberpunk 2077",
|
||||
"image": "game14",
|
||||
"price": 3400,
|
||||
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_14",
|
||||
"description": "RPG в киберпанк-сеттинге с нелинейным сюжетом и детализированным открытым миром.",
|
||||
"category": "RPG"
|
||||
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"title": "Age of Empires IV",
|
||||
"name": "Age of Empires IV",
|
||||
"image": "game15",
|
||||
"price": 3200,
|
||||
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_15",
|
||||
"description": "Классическая стратегия в реальном времени с историческими кампаниями.",
|
||||
"category": "Strategies"
|
||||
|
||||
},
|
||||
{
|
||||
"id": 16,
|
||||
"title": "Civilization VI",
|
||||
"name": "Civilization VI",
|
||||
"image": "game16",
|
||||
"price": 4200,
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_16",
|
||||
"description": "Глобальная пошаговая стратегия, в которой игроки строят и развивают цивилизации.",
|
||||
"category": "Strategies"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
@ -1,16 +0,0 @@
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
"ids": [
|
||||
3,
|
||||
13,
|
||||
1,
|
||||
10,
|
||||
4,
|
||||
9,
|
||||
15,
|
||||
6,
|
||||
7
|
||||
]
|
||||
}
|
||||
}
|
@ -3,51 +3,43 @@
|
||||
"data": {
|
||||
"topSail": [
|
||||
{
|
||||
"id": 1,
|
||||
"image": "game1",
|
||||
"price": 1500,
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_1"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"image": "game2",
|
||||
"price": 980,
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_2"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"image": "game3",
|
||||
"price": 1900,
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_3"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"image": "game4",
|
||||
"price": 1200,
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_4"
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"image": "game5",
|
||||
"price": 479,
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_5"
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"image": "game6",
|
||||
"price": 700,
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_6"
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"image": "game7",
|
||||
"price": 1100,
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_7"
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"image": "game8",
|
||||
"price": 3800,
|
||||
"text": "$10",
|
||||
"imgPath": "img_top_8"
|
||||
}
|
||||
],
|
||||
@ -105,27 +97,23 @@
|
||||
{
|
||||
"image": "news1",
|
||||
"text": "Разработчики Delta Force: Hawk Ops представили крупномасштабный режим Havoc Warfare",
|
||||
"imgPath": "img_news_1",
|
||||
"link": "https://gamemag.ru/news/185583/delta-force-hawk-ops-gameplay-showcase-havoc-warfare"
|
||||
"imgPath": "img_news_1"
|
||||
},
|
||||
{
|
||||
"image": "news2",
|
||||
"text": "Первый трейлер Assassin’s Creed Shadows — с темнокожим самураем в феодальной Японии",
|
||||
"imgPath": "img_news_2",
|
||||
"link": "https://stopgame.ru/newsdata/62686/pervyy_trailer_assassin_s_creed_shadows_s_temnokozhim_samuraem_v_feodalnoy_yaponii"
|
||||
"imgPath": "img_news_2"
|
||||
},
|
||||
{
|
||||
"image": "news3",
|
||||
"text": "Призрак Цусимы» вышел на ПК — и уже ставит рекорды для Sony",
|
||||
"imgPath": "img_news_3",
|
||||
"link": "https://stopgame.ru/newsdata/62706/prizrak_cusimy_vyshel_na_pk_i_uzhe_stavit_rekordy_dlya_sony"
|
||||
"imgPath": "img_news_3"
|
||||
},
|
||||
{
|
||||
"image": "news4",
|
||||
"text": "Авторы Skull and Bones расширяют планы на второй сезон",
|
||||
"imgPath": "img_news_4",
|
||||
"link": "https://stopgame.ru/newsdata/62711/avtory_skull_and_bones_rasshiryayut_plany_na_vtoroy_sezon"
|
||||
"text": "Авторы Skull and Bones расширяют планы на второй сезо",
|
||||
"imgPath": "img_news_4"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -788,121 +788,5 @@
|
||||
"image_url": "w_six"
|
||||
}
|
||||
]
|
||||
},
|
||||
"history": {
|
||||
"intro_text": "Let's see how well you know UNICS!",
|
||||
"intro_image": "culture",
|
||||
"questions": [
|
||||
{
|
||||
"question": "When was Kazan founded?",
|
||||
"options": [
|
||||
"1005",
|
||||
"1156",
|
||||
"1230",
|
||||
"1323"
|
||||
],
|
||||
"correct_answer": "1005",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "What is the main river flowing through Kazan?",
|
||||
"options": [
|
||||
"Volga",
|
||||
"Kazanka",
|
||||
"Kama",
|
||||
"Izh"
|
||||
],
|
||||
"correct_answer": "Kazanka",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Who was the first khan of Kazan?",
|
||||
"options": [
|
||||
"Ulugh Muhammad",
|
||||
"Akhmat",
|
||||
"Shah Ali",
|
||||
"Mamuka"
|
||||
],
|
||||
"correct_answer": "Ulugh Muhammad",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "What is the name of Kazan's main sports complex where the 2013 Universiade was held?",
|
||||
"options": [
|
||||
"Kazan Arena",
|
||||
"Tatneft Arena",
|
||||
"Bugulma Arena",
|
||||
"Ak Bars Sports Palace"
|
||||
],
|
||||
"correct_answer": "Kazan Arena",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Which mosque in Kazan is considered one of the largest in Russia?",
|
||||
"options": [
|
||||
"Kul Sharif Mosque",
|
||||
"Mari El Mosque",
|
||||
"Aisha Mosque",
|
||||
"Imam Muhammad Mosque"
|
||||
],
|
||||
"correct_answer": "Kul Sharif Mosque",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "What is the name of the square where the Kazan Kremlin and Kul Sharif Mosque are located?",
|
||||
"options": [
|
||||
"Vakhitov Square",
|
||||
"Freedom Square",
|
||||
"Kremlin Square",
|
||||
"Revolution Square"
|
||||
],
|
||||
"correct_answer": "Kremlin Square",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "What symbol of Kazan is depicted on the city's coat of arms?",
|
||||
"options": [
|
||||
"Dragon",
|
||||
"Tiger",
|
||||
"Lion",
|
||||
"Eagle"
|
||||
],
|
||||
"correct_answer": "Dragon",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Who was the architect of the Kazan Kremlin?",
|
||||
"options": [
|
||||
"Ivan Zarudny",
|
||||
"Fyodor Benjamin",
|
||||
"Andrey Ushakov",
|
||||
"Yury Dashevsky"
|
||||
],
|
||||
"correct_answer": "Andrey Ushakov",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Which of these universities is located in Kazan?",
|
||||
"options": [
|
||||
"Moscow State University",
|
||||
"Kazan Federal University",
|
||||
"St. Petersburg Polytechnic University",
|
||||
"Novosibirsk State University"
|
||||
],
|
||||
"correct_answer": "Kazan Federal University",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "What is the name of the largest street in Kazan, which is also the center of the city's nightlife?",
|
||||
"options": [
|
||||
"Kremlin Street",
|
||||
"Bauman Street",
|
||||
"Pushkin Street",
|
||||
"Kayum Nasyri Street"
|
||||
],
|
||||
"correct_answer": "Bauman Street",
|
||||
"image_url": "culture"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
@ -788,121 +788,5 @@
|
||||
"image_url": "w_six"
|
||||
}
|
||||
]
|
||||
},
|
||||
"history": {
|
||||
"intro_text": "Давайте узнаем, насколько вы хорошо знаете историю Казани!",
|
||||
"intro_image": "culture",
|
||||
"questions": [
|
||||
{
|
||||
"question": "Когда Казань была основана?",
|
||||
"options": [
|
||||
"1000 год",
|
||||
"1156 год",
|
||||
"1230 год",
|
||||
"1323 год"
|
||||
],
|
||||
"correct_answer": "1000 год",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Как называется главная река, протекающая через Казань?",
|
||||
"options": [
|
||||
"Волга",
|
||||
"Казанка",
|
||||
"Кама",
|
||||
"Иж"
|
||||
],
|
||||
"correct_answer": "Казанка",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Кто был первым казанским ханом?",
|
||||
"options": [
|
||||
"Улу-Мухаммед",
|
||||
"Ахмат",
|
||||
"Шах-Али",
|
||||
"Мамука"
|
||||
],
|
||||
"correct_answer": "Улу-Мухаммед",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Как называется главный спортивный комплекс Казани, где проводились Универсиада 2013 года?",
|
||||
"options": [
|
||||
"Казан Арена",
|
||||
"Татнефть Арена",
|
||||
"Бугульминская арена",
|
||||
"Дворец спорта \"Ак Барс\""
|
||||
],
|
||||
"correct_answer": "Казан Арена",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Какая мечеть в Казани считается одной из самых больших в России?",
|
||||
"options": [
|
||||
"Мечеть Кул Шариф",
|
||||
"Мечеть Марий Эл",
|
||||
"Мечеть Айша",
|
||||
"Мечеть имама Мухаммада"
|
||||
],
|
||||
"correct_answer": "Мечеть Кул Шариф",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Как называется площадь, на которой расположены Казанский Кремль и мечеть Кул Шариф?",
|
||||
"options": [
|
||||
"Площадь Вахитова",
|
||||
"Площадь Свободы",
|
||||
"Площадь Кремля",
|
||||
"Площадь Революции"
|
||||
],
|
||||
"correct_answer": "Площадь Кремля",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Какой символ Казани изображён на гербе города?",
|
||||
"options": [
|
||||
"Дракон",
|
||||
"Тигр",
|
||||
"Лев",
|
||||
"Орел"
|
||||
],
|
||||
"correct_answer": "Дракон",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Какой архитектор спроектировал Казанский Кремль?",
|
||||
"options": [
|
||||
"Иван Зарудный",
|
||||
"Фёдор Бенжамин",
|
||||
"Андрей Ушаков",
|
||||
"Юрий Дашевский"
|
||||
],
|
||||
"correct_answer": "Андрей Ушаков",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Какой из этих вузов находится в Казани?",
|
||||
"options": [
|
||||
"Московский государственный университет",
|
||||
"Казанский федеральный университет",
|
||||
"Санкт-Петербургский политехнический университет",
|
||||
"Новосибирский государственный университет"
|
||||
],
|
||||
"correct_answer": "Казанский федеральный университет",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Как называется крупнейшая в Казани улица, которая также является центром ночной жизни города?",
|
||||
"options": [
|
||||
"Кремлевская улица",
|
||||
"Баумана улица",
|
||||
"Пушкина улица",
|
||||
"Каюма Насыри улица"
|
||||
],
|
||||
"correct_answer": "Баумана улица",
|
||||
"image_url": "culture"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
@ -788,121 +788,5 @@
|
||||
"image_url": "w_six"
|
||||
}
|
||||
]
|
||||
},
|
||||
"history": {
|
||||
"intro_text": "Әйдәгез, Казан тарихын белүегезне ачыклыйк!",
|
||||
"intro_image": "culture",
|
||||
"questions": [
|
||||
{
|
||||
"question": "Казан кайчан нигезләнгән?",
|
||||
"options": [
|
||||
"1000 ел",
|
||||
"1156 ел",
|
||||
"1230 ел",
|
||||
"1323 ел"
|
||||
],
|
||||
"correct_answer": "1000 ел",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Казан аша агучы төп елга ничек атала?",
|
||||
"options": [
|
||||
"Идел",
|
||||
"Казанка",
|
||||
"Кама",
|
||||
"Иж"
|
||||
],
|
||||
"correct_answer": "Казанка",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Казанның беренче ханы кем булган?",
|
||||
"options": [
|
||||
"Олуг Мөхәммәт",
|
||||
"Әхмәт",
|
||||
"Шаһ-Әли",
|
||||
"Мамука"
|
||||
],
|
||||
"correct_answer": "Олуг Мөхәммәт",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "2013 елда Универсиада узган Казанның төп спорт комплексы ничек атала?",
|
||||
"options": [
|
||||
"Казан Арена",
|
||||
"Татнефть Арена",
|
||||
"Бөгелмә Арена",
|
||||
"Ак Барс спорт сарае"
|
||||
],
|
||||
"correct_answer": "Казан Арена",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Казандагы иң зур мәчетләрнең берсе Россиядәге кайсысы?",
|
||||
"options": [
|
||||
"Кол Шәриф мәчете",
|
||||
"Марий Эл мәчете",
|
||||
"Айша мәчете",
|
||||
"Имам Мөхәммәт мәчете"
|
||||
],
|
||||
"correct_answer": "Кол Шәриф мәчете",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Казан Кремле һәм Кол Шәриф мәчете урнашкан мәйдан ничек атала?",
|
||||
"options": [
|
||||
"Вахитов мәйданы",
|
||||
"Ирек мәйданы",
|
||||
"Кремль мәйданы",
|
||||
"Революция мәйданы"
|
||||
],
|
||||
"correct_answer": "Кремль мәйданы",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Казан гербында кайсы символ сурәтләнгән?",
|
||||
"options": [
|
||||
"Аждаһа",
|
||||
"Юлбарыс",
|
||||
"Арслан",
|
||||
"Бүре"
|
||||
],
|
||||
"correct_answer": "Аждаһа",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Казан Кремленең архитекторын атагыз.",
|
||||
"options": [
|
||||
"Иван Зарудный",
|
||||
"Фёдор Бенжамин",
|
||||
"Андрей Ушаков",
|
||||
"Юрий Дашевский"
|
||||
],
|
||||
"correct_answer": "Андрей Ушаков",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Бу югары уку йортларының кайсысы Казанда урнашкан?",
|
||||
"options": [
|
||||
"Мәскәү дәүләт университеты",
|
||||
"Казан федераль университеты",
|
||||
"Санкт-Петербург политехник университеты",
|
||||
"Новосибирск дәүләт университеты"
|
||||
],
|
||||
"correct_answer": "Казан федераль университеты",
|
||||
"image_url": "culture"
|
||||
},
|
||||
{
|
||||
"question": "Казандагы иң зур урам ничек атала? Ул шулай ук шәһәрнең төнге тормыш үзәге булып тора.",
|
||||
"options": [
|
||||
"Кремль урамы",
|
||||
"Бауман урамы",
|
||||
"Пушкин урамы",
|
||||
"Каюм Насыйри урамы"
|
||||
],
|
||||
"correct_answer": "Бауман урамы",
|
||||
"image_url": "culture"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
@ -1,26 +1 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"description": "10 слов в Data Science",
|
||||
"imageFilename": "kart1.jpg",
|
||||
"words": [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"description": "Job Interview",
|
||||
"imageFilename": "kart1.jpg",
|
||||
"words": [13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"description": "ReactJS",
|
||||
"imageFilename": "kart1.jpg",
|
||||
"words": [23, 24, 25, 26, 27, 28, 29, 30, 31, 32]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"description": "NodeJS",
|
||||
"imageFilename": "kart1.jpg",
|
||||
"words": [33, 34, 35, 36, 37, 38, 39, 40, 41, 42]
|
||||
}
|
||||
]
|
||||
[{"id":1,"description":"10 слов в Data Science","imageFilename":"kart1.jpg","words":[2,3,4,5,6,7,8,9,10,11,12]}]
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -607,7 +607,8 @@ function createGigachat(options = {}) {
|
||||
}
|
||||
var gigachat = createGigachat();
|
||||
// Annotate the CommonJS export names for ESM import in node:
|
||||
module.exports = {
|
||||
0 && (module.exports = {
|
||||
createGigachat,
|
||||
gigachat
|
||||
}
|
||||
});
|
||||
//# sourceMappingURL=index.js.map
|
@ -84,7 +84,7 @@ router.use(async (req, res, next) => {
|
||||
process.env.GIGACHAT_ACCESS_TOKEN = json.access_token;
|
||||
process.env.GIGACHAT_EXPIRES_AT = json.expires_at;
|
||||
console.log(JSON.stringify(response.data));
|
||||
} catch (error) {
|
||||
} catch {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
|
@ -1,10 +1,8 @@
|
||||
const router = require('express').Router();
|
||||
|
||||
const wordsRouter = require('./words');
|
||||
const dictionariesRouter = require('./dictionaries');
|
||||
const unitsRouter = require('./units');
|
||||
const gigachatRouter = require('./gigachat');
|
||||
const usersRouter = require('./users');
|
||||
module.exports = router;
|
||||
|
||||
const delay =
|
||||
@ -14,8 +12,6 @@ const delay =
|
||||
};
|
||||
|
||||
router.use(delay());
|
||||
router.use('/words', wordsRouter);
|
||||
router.use('/dictionaries', dictionariesRouter);
|
||||
router.use('/units', unitsRouter);
|
||||
router.use('/gigachat', gigachatRouter);
|
||||
router.use('/users', usersRouter);
|
||||
router.use('/gigachat', gigachatRouter);
|
@ -4,45 +4,9 @@ const router = require('express').Router();
|
||||
|
||||
module.exports = router;
|
||||
|
||||
const data = require('./units.json');
|
||||
const data = require('./data/units.json');
|
||||
router.get('/', (req, res) => {
|
||||
// for every data set author from users and save it to authoredData variable
|
||||
const users = require('../users/users.json');
|
||||
const authoredData = data.map((unit) => {
|
||||
const user = users.find((user) => user.public_id == unit.author);
|
||||
let authoredUnit = undefined;
|
||||
if (user) {
|
||||
authoredUnit = { ...unit, author: user };
|
||||
}
|
||||
return authoredUnit;
|
||||
});
|
||||
|
||||
res.send(authoredData);
|
||||
});
|
||||
|
||||
router.post('/:id', (req, res) => {
|
||||
const id = parseInt(req.params.id);
|
||||
const updatedUnit = req.body;
|
||||
|
||||
if (!updatedUnit) {
|
||||
return res.status(400).send('No unit to be added');
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return res.status(500).send('No data to be updated');
|
||||
}
|
||||
|
||||
const index = data.findIndex((unit) => unit.id === id);
|
||||
|
||||
if (index < 0) {
|
||||
return res.status(404).send('Not found');
|
||||
}
|
||||
|
||||
data.splice(index, 1);
|
||||
|
||||
data.push({...updatedUnit, author: updatedUnit.author.public_id});
|
||||
|
||||
res.status(200).send(data);
|
||||
res.send(data);
|
||||
});
|
||||
|
||||
router.put('/', (req, res) => {
|
||||
@ -52,17 +16,17 @@ router.put('/', (req, res) => {
|
||||
return res.status(400).send('No new unit to be added');
|
||||
}
|
||||
|
||||
if (!newUnit.author) {
|
||||
return res.status(400).send('User is not logged in!');
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return res.status(500).send('No data to be updated');
|
||||
}
|
||||
|
||||
const newId = data.length + 1;
|
||||
data.push({ ...newUnit, id: newId });
|
||||
const filename = newUnit.name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
|
||||
fs.writeFileSync(path.join(__dirname, 'data', `${filename}.md`), newUnit.content);
|
||||
|
||||
data.push({ id: newId, filename: filename, name: newUnit.name });
|
||||
|
||||
fs.writeFileSync(path.join(__dirname, 'data', 'units.json'), JSON.stringify(data));
|
||||
res.status(200).send(data);
|
||||
});
|
||||
|
||||
@ -75,19 +39,24 @@ router.delete('/:id', (req, res) => {
|
||||
}
|
||||
|
||||
data.splice(index, 1);
|
||||
fs.writeFileSync(path.join(__dirname, 'data', 'units.json'), JSON.stringify(data));
|
||||
res.send({ message: `Unit with ID ${id} deleted` });
|
||||
});
|
||||
|
||||
router.get('/:id', (req, res) => {
|
||||
const users = require('../users/users.json');
|
||||
const id = parseInt(req.params.id);
|
||||
const unit = data.find((unit) => unit.id === id);
|
||||
|
||||
if (!unit) {
|
||||
return res.status(404).send('Unit not found');
|
||||
return res.status(404).send('Not found');
|
||||
}
|
||||
|
||||
const user = users.find((user) => user.public_id == unit.author);
|
||||
const unitFilepath = path.join(__dirname, 'data', `${unit.filename}.md`);
|
||||
const unitContent = fs.readFileSync(unitFilepath, 'utf-8');
|
||||
|
||||
res.send({...unit, author: user});
|
||||
if (!unitContent) {
|
||||
return res.status(404).send('Not found');
|
||||
}
|
||||
|
||||
res.send({ ...unit, content: unitContent });
|
||||
});
|
||||
|
@ -1,20 +0,0 @@
|
||||
[
|
||||
{
|
||||
"content": "# Цель урока\n\nИзучение структуры документации программы с блоком кода.\n\n## Лексика\n\n### Базовая лексика:\n\n- Documentation – документация\n- Code block – блок кода\n- Description – описание\n- Function – функция\n- Variable – переменная\n- Comment – комментарий\n\n### Расширенная лексика:\n\n- API – интерфейс прикладного программирования\n- Method – метод\n- Class – класс\n- Library – библиотека\n- Framework – фреймворк\n\n## Грамматический фокус\n\nПравило: Структура документации программы должна включать краткое описание, блок кода и примеры использования.\n\nПример:\n\nDocumentation for a program typically includes the following sections:\n\n1. **Description**: A brief overview of what the program does and its purpose.\n2. **Code Block**: The actual code that implements the functionality described in the first section.\n3. **Examples**: One or more examples demonstrating how to use the features described in the documentation.\n\nТипичные ошибки и как их избежать: Ошибки могут возникнуть из-за недостаточного описания функционала или неправильного форматирования кода. Чтобы избежать этого, важно тщательно проработать каждый раздел документации и убедиться, что все примеры корректны и понятны.\n\n## Контекстуализация\n\nТекст для анализа:\n\n**Description**: This is a simple Python script that calculates the average value of a list of numbers.\n\n**Code Block**: \n```python\ndef calculate_average(numbers):\n \"\"\"Calculate the average value of a list of numbers\"\"\"\n return sum(numbers)/len(numbers)\n```\n\nПримеры использования:\n\n```python\n# Example usage\nnumbers = [10, 20, 30]\naverage = calculate_average(numbers)\nprint(\"The average value of the list\", numbers, \"is\", average)\n```\n\n## Упражнения\n\nПисьменное задание: Написать документацию для простой функции на языке Python, которая принимает список чисел и возвращает среднее значение. Включить описание, код блока и пример использования.\n\nУстная практика: Ролевой диалог между разработчиком и техническим писателем о структуре и содержании документации программы.\n\nАналитическое задание: Проанализировать существующую документацию программы и найти ошибки или неясности. Предложить улучшения.\n\n## Домашнее задание\n\nТекстовые задачи:\n\n- Написать документацию для другой функции на языке Python, используя правильную структуру.\n- Исправить ошибки в существующей документации программы.\n- Перевести фрагмент документации на русский язык, сохраняя точность и стиль.\n",
|
||||
"id": 2,
|
||||
"author": "1738707541324",
|
||||
"name": "Документация программы"
|
||||
},
|
||||
{
|
||||
"content": "### Цель урока:\nИзучение ключевых слов и фраз, связанных с процессом трудоустройства, а также освоение базовой структуры диалога на собеседовании.\n\n### Лексика:\n**Базовая лексика:**\n1. **Job interview** – собеседование при приеме на работу\n2. **Resume / CV** – резюме\n3. **Cover letter** – сопроводительное письмо\n4. **Interviewer** – интервьюер\n5. **Application form** – анкета при приеме на работу\n6. **Salary** – зарплата\n7. **Benefits** – льготы\n\n**Расширенная лексика:**\n1. **To apply for a job** – подавать заявку на работу\n2. **To be offered the job** – получить предложение о работе\n3. **To negotiate salary** – вести переговоры о зарплате\n4. **To accept the offer** – принять предложение\n5. **To decline the offer** – отклонить предложение\n6. **To resign from your current position** – подать заявление об уходе с текущей работы\n7. **To start working at the company** – начать работать в компании\n8. **Probation period** – испытательный срок\n9. **References** – рекомендации\n10. **Work experience** – опыт работы\n\n### Грамматический фокус:\n**Правило:**\nСтруктура простого вопроса на английском языке:\n- Общий вопрос: \"Do you have any questions?\"\n- Специальный вопрос: \"What are your strengths and weaknesses?\"\n\n**Пример:**\nОбщий вопрос: \"How do you feel about this job opportunity?\"\nСпециальный вопрос: \"Can you tell me about your previous work experience?\"\n\n**Типичные ошибки и как их избежать:**\nОшибка: Неправильное использование порядка слов в вопросах.\nРешение: Практиковать построение вопросов до автоматизма.\n\n### Контекстуализация:\n**Текст для анализа:**\n\"I'm applying for the position of a marketing manager at XYZ Company. Here is my resume.\"\n\"Thank you for considering me. Can you please tell me more about the responsibilities of this role?\"\n\"Sure, let me give you an overview.\"\n\n### Упражнения:\n**Письменное задание:**\nСоставьте список из 5 вопросов, которые вы бы задали на собеседовании. Используйте простые вопросы и специальные вопросы.\n\n**Устная практика:**\nРолевая игра: один студент играет роль интервьюера, другой – кандидата на должность. Меняйтесь ролями.\n\n**Аналитическое задание:**\nНайдите и исправьте ошибки в следующем письме:\n\"Dear HR Manager,\n\nMy name is John Smith and I am writing to apply for the position of Sales Representative at ABC Inc. I enclose my resume for your review.\n\nI believe that my skills and experiences make me an ideal candidate for this position. In my current role as a sales representative at XYZ Corp, I have consistently met or exceeded my sales targets. Additionally, I possess strong communication and negotiation skills which will enable me to effectively represent your products and services.\n\nIf you would like to schedule an interview, please contact me at your convenience. Thank you for your time and consideration.\n\nBest regards,\nJohn Smith\"\n\n### Домашнее задание:\n**Текстовые задачи:**\n1. Написать сопроводительное письмо для конкретной вакансии, используя расширенную лексику.\n2. Составить резюме для воображаемой должности, включая все необходимые разделы.\n3. Перевести текст собеседования на английский язык, сохраняя структуру и смысл.",
|
||||
"id": 3,
|
||||
"author": "1738707541324",
|
||||
"name": "Job Interview"
|
||||
},
|
||||
{
|
||||
"content": "# Multifunctional Verbs\n\n## Overview\n\nThis unit focuses on the use of multifunctional verbs in English. These verbs are able to express multiple meanings depending on their use in a sentence.\n\n## Learning Objectives\n\nBy the end of this unit, you will be able to:\n\n* Identify the different forms of the main multifunctional verb.\n* Explain how these forms can be used interchangeably in sentences.\n* Demonstrate the correct usage of the three forms of the multifunctional verb by providing sentences and examples.\n\n## Vocabulary Review\n\n| Term | Definition |\n| ---- | -------------------------------------------------------- |\n| Be | To express a present or ongoing state of being. |\n| Have | To express ownership or possession. |\n| Do | To express an action to be done, future action or habit. |\n\n## Activities\n\n### Activity 1: Identify the Different Forms of the Main Multifunctional Verb\n\n* Read through each sentence and identify if the verb is used in its present tense (is), past tense (was/were), or future tense (will, would).\n* Discuss how this usage can vary depending on context.\n* Write down sentences that use different forms to illustrate your points.\n\n1. **Sentence 1**\n\n : \"The cat is sleeping.\"\n * Present tense: The cat is sleeping.\n * Past tense: The cat slept.\n * Future tense: The cat will sleep.\n2. **Sentence 2**\n\n : \"I have a dog at home.\"\n * Present tense: I have a dog.\n * Past tense: I had a dog.\n * Future tense: I will have a dog.\n3. **Sentence 3**\n\n : \"We are going on a hike tomorrow.\"\n * Present tense: We are going on a hike.\n * Past tense: We went on a hike.\n * Future tense: We will go on a hike.\n4. **Sentence 4**\n\n : \"He has been studying all day.\"\n * Present tense: He is studying.\n * Past tense: He studied.\n * Future tense: He will study.\n5. **Sentence 5**\n\n : \"We are going to buy some groceries later today.\"\n * Present tense: We are going to buy some groceries.\n * Past tense: We bought some groceries.\n * Future tense: We will buy some groceries.\n\n### Activity 2: Explain How These Forms Can Be Used Interchangeably in Sentences\n\n* Read through a sentence and identify the present, past, and future tense uses.\n* In pairs, explain why these forms are used interchangeably.\n* Provide examples of sentences that demonstrate this usage.\n* Highlight how the context changes the meaning.\n\n### Activity 3: Correct Usage of the Three Forms of the Multifunctional Verb\n\n* Read through a sentence and identify which form is being used.\n* In pairs, discuss why these forms are used in certain situations.\n* Provide sentences that demonstrate the correct usage of the three forms.",
|
||||
"id": 1,
|
||||
"author": "1738707541324",
|
||||
"name": "Multifunctional Verbs"
|
||||
}
|
||||
]
|
@ -1,53 +0,0 @@
|
||||
const router = require('express').Router();
|
||||
const fs = require('fs');
|
||||
|
||||
module.exports = router;
|
||||
|
||||
let data = require('./users.json');
|
||||
const path = require('path');
|
||||
router.get('/', (req, res) => {
|
||||
res.send(data);
|
||||
});
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
const newUser = req.body;
|
||||
|
||||
data.push(newUser);
|
||||
fs.writeFileSync(path.join(__dirname, 'users.json'), JSON.stringify(data));
|
||||
res.send(data);
|
||||
});
|
||||
|
||||
router.post('/login', (req, res) => {
|
||||
const { email, password } = req.body;
|
||||
const user = data.find((user) => user.email === email && user.password === password);
|
||||
|
||||
if (!user) {
|
||||
res.status(404).send('Пользователь не найден');
|
||||
}
|
||||
res.json({ public_id: user.public_id });
|
||||
});
|
||||
|
||||
router.get('/account', (req, res) => {
|
||||
const { public_id } = req.query;
|
||||
const user = data.find((user) => user.public_id == public_id);
|
||||
|
||||
if (!user) {
|
||||
res.status(404).send('Пользователь не найден');
|
||||
}
|
||||
res.send({ ...user, id: -1 });
|
||||
});
|
||||
|
||||
router.post('/account/save', (req, res) => {
|
||||
const updatedUser = req.body;
|
||||
const { public_id } = updatedUser;
|
||||
const index = data.findIndex((user) => user.public_id == public_id);
|
||||
|
||||
if (!index || index === -1) {
|
||||
res.status(404).send('Пользователь не найден');
|
||||
}
|
||||
|
||||
data[index] = { ...data[index], ...updatedUser, id: data[index].id, password: data[index].password };
|
||||
fs.writeFileSync(path.join(__dirname, 'users.json'), JSON.stringify(data));
|
||||
|
||||
res.status(200);
|
||||
});
|
@ -1 +0,0 @@
|
||||
[{"id":1738707541324,"public_id":1738707541324,"email":"1@gmail.com","password":"1","age":"22","nickname":"324324","about":"Чиловый "}]
|
@ -132,306 +132,5 @@
|
||||
"During model validation, its ability to make accurate predictions on new data is checked.",
|
||||
"Validation showed that the model is robust against changes in data and has low generalization error."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"word": "resume",
|
||||
"translation": "резюме",
|
||||
"definition": "a document containing a summary of your work experience, education, and skills that you submit when applying for a job",
|
||||
"synonyms": ["CV", "curriculum vitae"],
|
||||
"examples": [
|
||||
"Make sure to update your resume before the interview."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"word": "interviewer",
|
||||
"translation": "интервьюер",
|
||||
"definition": "the person who conducts an interview, typically a representative of the company or organization offering the job",
|
||||
"synonyms": ["questioner", "examiner"],
|
||||
"examples": [
|
||||
"The interviewer asked about my previous work experiences."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"word": "qualification",
|
||||
"translation": "квалификация",
|
||||
"definition": "a quality, skill, or attribute that makes someone suitable for a particular job or activity",
|
||||
"synonyms": ["credential", "competence"],
|
||||
"examples": [
|
||||
"Do you have any qualifications in project management?"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 16,
|
||||
"word": "experience",
|
||||
"translation": "опыт",
|
||||
"definition": "practical contact with and observation of facts or events, especially those gained through employment",
|
||||
"synonyms": ["background", "track record"],
|
||||
"examples": [
|
||||
"She has five years of experience in marketing."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 17,
|
||||
"word": "skillset",
|
||||
"translation": "набор навыков",
|
||||
"definition": "the range of skills and abilities possessed by an individual",
|
||||
"synonyms": ["abilities", "talents"],
|
||||
"examples": [
|
||||
"Her skillset includes proficiency in several programming languages."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 18,
|
||||
"word": "cover letter",
|
||||
"translation": "сопроводительное письмо",
|
||||
"definition": "a document sent with your resume that provides additional information on why you're qualified for the position",
|
||||
"synonyms": ["application letter", "letter of introduction"],
|
||||
"examples": [
|
||||
"Always include a well-written cover letter with your application."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 19,
|
||||
"word": "hiring manager",
|
||||
"translation": "менеджер по найму",
|
||||
"definition": "the person responsible for making hiring decisions within a company or department",
|
||||
"synonyms": ["recruiter", "HR manager"],
|
||||
"examples": [
|
||||
"The hiring manager will review all applications and select candidates for interviews."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 20,
|
||||
"word": "job description",
|
||||
"translation": "описание вакансии",
|
||||
"definition": "a detailed account of the responsibilities, duties, required skills, and working conditions associated with a specific job",
|
||||
"synonyms": ["position profile", "role specification"],
|
||||
"examples": [
|
||||
"Read the job description carefully to understand what the employer is looking for."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 21,
|
||||
"word": "salary negotiation",
|
||||
"translation": "переговоры о зарплате",
|
||||
"definition": "the process of discussing and agreeing upon the compensation for a job, including salary, benefits, and other forms of remuneration",
|
||||
"synonyms": ["compensation discussion", "pay bargaining"],
|
||||
"examples": [
|
||||
"It's important to prepare for salary negotiations during the final stages of the interview process."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 22,
|
||||
"word": "reference",
|
||||
"translation": "рекомендация",
|
||||
"definition": "a person who can vouch for your qualifications, character, and work ethic, often contacted by potential employers",
|
||||
"synonyms": ["endorsement", "testimonial"],
|
||||
"examples": [
|
||||
"Be prepared to provide references from former supervisors or colleagues."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 23,
|
||||
"word": "component",
|
||||
"translation": "компонент",
|
||||
"definition": "A reusable piece of code that renders part of the user interface.",
|
||||
"synonyms": ["module", "widget"],
|
||||
"examples": [
|
||||
"In React, components are the building blocks of the UI."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 24,
|
||||
"word": "props",
|
||||
"translation": "пропсы",
|
||||
"definition": "Short for 'properties', these are read-only components passed down from parent components to child components.",
|
||||
"synonyms": ["attributes", "parameters"],
|
||||
"examples": [
|
||||
"Props allow you to pass data between components."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 25,
|
||||
"word": "state",
|
||||
"translation": "состояние",
|
||||
"definition": "An object that holds data specific to a component which may change over time.",
|
||||
"synonyms": ["data", "context"],
|
||||
"examples": [
|
||||
"Managing state is crucial for dynamic web applications."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 26,
|
||||
"word": "render",
|
||||
"translation": "рендеринг",
|
||||
"definition": "The process of updating the DOM to match the current state of a component.",
|
||||
"synonyms": ["update", "refresh"],
|
||||
"examples": [
|
||||
"React efficiently handles rendering to ensure smooth updates."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 27,
|
||||
"word": "virtual DOM",
|
||||
"translation": "виртуальный DOM",
|
||||
"definition": "A lightweight copy of the actual DOM maintained by React to improve performance by minimizing updates to the real DOM.",
|
||||
"synonyms": ["shadow tree", "virtual representation"],
|
||||
"examples": [
|
||||
"Virtual DOM allows React to update only necessary parts of the UI."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 28,
|
||||
"word": "JSX",
|
||||
"translation": "JSX",
|
||||
"definition": "A syntax extension to JavaScript used in React to describe what the user interface should look like.",
|
||||
"synonyms": ["template language", "syntax extension"],
|
||||
"examples": [
|
||||
"JSX makes it easier to write and understand React components."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 29,
|
||||
"word": "hooks",
|
||||
"translation": "хуки",
|
||||
"definition": "Functions that let you use state and other React features without writing a class.",
|
||||
"synonyms": ["functionalities", "utilities"],
|
||||
"examples": [
|
||||
"Hooks make functional components more powerful."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 30,
|
||||
"word": "event handling",
|
||||
"translation": "обработка событий",
|
||||
"definition": "The mechanism by which React components respond to user actions such as clicks, key presses, etc.",
|
||||
"synonyms": ["interaction management", "action response"],
|
||||
"examples": [
|
||||
"Event handlers in React allow you to define how components react to user interactions."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 31,
|
||||
"word": "lifecycle methods",
|
||||
"translation": "методы жизненного цикла",
|
||||
"definition": "Methods called at different stages of a component's existence, allowing developers to perform tasks at each stage.",
|
||||
"synonyms": ["phase callbacks", "stage handlers"],
|
||||
"examples": [
|
||||
"Lifecycle methods help manage the behavior of components throughout their lifecycle."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 32,
|
||||
"word": "routing",
|
||||
"translation": "маршрутизация",
|
||||
"definition": "The process of defining and managing navigation paths within a single-page application.",
|
||||
"synonyms": ["navigation control", "path management"],
|
||||
"examples": [
|
||||
"React Router is commonly used for routing in React apps."
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
"id": 33,
|
||||
"word": "server-side",
|
||||
"translation": "серверная сторона",
|
||||
"definition": "Refers to operations performed by the server in contrast to client-side operations.",
|
||||
"synonyms": ["backend", "back-end"],
|
||||
"examples": [
|
||||
"Node.js is primarily used for server-side development."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 34,
|
||||
"word": "asynchronous",
|
||||
"translation": "асинхронный",
|
||||
"definition": "Programming model where operations execute independently of other operations, allowing efficient handling of multiple requests simultaneously.",
|
||||
"synonyms": ["non-blocking", "concurrent"],
|
||||
"examples": [
|
||||
"Node.js uses asynchronous I/O to handle many concurrent connections efficiently."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 35,
|
||||
"word": "callback",
|
||||
"translation": "коллбек",
|
||||
"definition": "A function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.",
|
||||
"synonyms": ["handler", "continuation"],
|
||||
"examples": [
|
||||
"Callbacks are widely used in Node.js for handling asynchronous operations."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 36,
|
||||
"word": "event loop",
|
||||
"translation": "цикл событий",
|
||||
"definition": "Mechanism in Node.js that handles asynchronous operations and ensures non-blocking I/O by offloading operations to the system kernel whenever possible.",
|
||||
"synonyms": ["event-driven architecture", "runtime environment"],
|
||||
"examples": [
|
||||
"The event loop is fundamental to understanding how Node.js works."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 37,
|
||||
"word": "package manager",
|
||||
"translation": "менеджер пакетов",
|
||||
"definition": "Tool used to install, update, configure, and remove packages in Node.js projects.",
|
||||
"synonyms": ["dependency manager", "library manager"],
|
||||
"examples": [
|
||||
"npm and yarn are popular package managers for Node.js."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 38,
|
||||
"word": "middleware",
|
||||
"translation": "промежуточное ПО",
|
||||
"definition": "Software that sits between an application and the backend infrastructure, providing additional functionality to the request-response cycle.",
|
||||
"synonyms": ["interceptor", "filter"],
|
||||
"examples": [
|
||||
"Express.js uses middleware to handle common tasks like logging, authentication, and error handling."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 39,
|
||||
"word": "REST API",
|
||||
"translation": "REST API",
|
||||
"definition": "Architectural style for building APIs using HTTP methods to perform CRUD operations on resources.",
|
||||
"synonyms": ["web service", "API design pattern"],
|
||||
"examples": [
|
||||
"Many Node.js applications implement RESTful APIs to communicate with clients."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 40,
|
||||
"word": "streams",
|
||||
"translation": "потоки",
|
||||
"definition": "Data structures that facilitate continuous transfer of data in chunks rather than loading everything into memory at once.",
|
||||
"synonyms": ["data flow", "pipeline"],
|
||||
"examples": [
|
||||
"Streams are useful for handling large files or continuous data in Node.js."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 41,
|
||||
"word": "cluster module",
|
||||
"translation": "модуль кластера",
|
||||
"definition": "Built-in module in Node.js that allows an application to be split into multiple processes running on separate CPU cores, improving performance and scalability.",
|
||||
"synonyms": ["multi-processing", "parallel execution"],
|
||||
"examples": [
|
||||
"Using the cluster module can significantly enhance the throughput of a Node.js application."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 42,
|
||||
"word": "event emitter",
|
||||
"translation": "излучатель событий",
|
||||
"definition": "Class in Node.js that facilitates communication between objects in an application by emitting named events that other objects can listen to.",
|
||||
"synonyms": ["publisher-subscriber", "observer pattern"],
|
||||
"examples": [
|
||||
"Event emitters are useful for implementing custom event-based systems in Node.js."
|
||||
]
|
||||
}
|
||||
]
|
||||
|
@ -27,12 +27,10 @@ router.post('/:user_id/:action/:id', (req, res) => {
|
||||
const user_id = parseInt(req.params.user_id);
|
||||
const id = parseInt(req.params.id);
|
||||
const action = req.params.action;
|
||||
/*
|
||||
if (users_data.findIndex((item) => item.id === user_id) === -1 || data.findIndex((item) => item.id === id) === -1) {
|
||||
res.status(404).send();
|
||||
return;
|
||||
}
|
||||
*/
|
||||
if (action !== 'participate' && action !== 'refuse') {
|
||||
res.status(400).send({ error: 'Invalid action' });
|
||||
return;
|
||||
|
@ -10,17 +10,6 @@
|
||||
"Музыка"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 1252744945,
|
||||
"username": "Моряков Сергей",
|
||||
"photo": "",
|
||||
"about": "Люблю путешествия и фотографию, обожаю изучать новые культуры.",
|
||||
"email": "sergey.moryakov@example.com",
|
||||
"interests": [
|
||||
"Путешествия и туризм",
|
||||
"Искусство, фотография и дизайн"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"username": "Мария Смирнова",
|
||||
@ -229,5 +218,16 @@
|
||||
"Медицина и здоровье",
|
||||
"Спорт, фитнес и ЗОЖ"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 1252744945,
|
||||
"username": "Моряков Сергей",
|
||||
"photo": "https://i.pravatar.cc/150?img=50",
|
||||
"about": "Люблю путешествия и фотографию, обожаю изучать новые культуры.",
|
||||
"email": "maria.smirnova@example.com",
|
||||
"interests": [
|
||||
"Путешествия и туризм",
|
||||
"Искусство, фотография и дизайн"
|
||||
]
|
||||
}
|
||||
]
|
@ -27,12 +27,10 @@ router.post('/:to_id/:action/:from_id', (req, res) => {
|
||||
const to_id = parseInt(req.params.to_id);
|
||||
const from_id = parseInt(req.params.from_id);
|
||||
const action = req.params.action;
|
||||
/*
|
||||
if (data.findIndex((item) => item.id === to_id) === -1 || data.findIndex((item) => item.id === from_id) === -1) {
|
||||
res.status(404).send();
|
||||
return;
|
||||
}
|
||||
*/
|
||||
if (action !== 'like' && action !== 'dislike') {
|
||||
res.status(400).send({ error: 'Invalid action' });
|
||||
return;
|
||||
|
@ -5,11 +5,9 @@ const router = Router()
|
||||
const todoRouter = require('./routes')
|
||||
const authRouter = require('./auth')
|
||||
const commentRouter = require('./comment')
|
||||
const navRouter = require('./nav')
|
||||
|
||||
router.use('/auth', authRouter)
|
||||
router.use('/comment', commentRouter)
|
||||
router.use('/nav', navRouter)
|
||||
|
||||
router.use(todoRouter)
|
||||
|
||||
|
@ -1,51 +0,0 @@
|
||||
const router = require("express").Router();
|
||||
|
||||
router.get("/users", (req, res) => {
|
||||
res.send({
|
||||
success: false,
|
||||
body: [
|
||||
{
|
||||
id: "some-user-id",
|
||||
name: "alexandr",
|
||||
age: 38,
|
||||
surname: null,
|
||||
email: null,
|
||||
rated: 4,
|
||||
avatar:
|
||||
"https://www.gravatar.com/avatar/6529e885535ef67a3fad810ad71167c2c03f79480936e9b3a714731753cbb47e?d=robohash",
|
||||
friends: [
|
||||
{
|
||||
id: "2",
|
||||
name: "not alexandr",
|
||||
surname: null,
|
||||
email: null,
|
||||
rated: 2,
|
||||
avatar: "https://www.gravatar.com/avatar/6e?d=robohash",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
name: "not alexandr",
|
||||
surname: null,
|
||||
email: null,
|
||||
age: 24,
|
||||
rated: 5,
|
||||
avatar: "https://www.gravatar.com/avatar/6e?d=robohash",
|
||||
friends: [
|
||||
{
|
||||
id: "some-user-id",
|
||||
name: "alexandr",
|
||||
surname: null,
|
||||
email: null,
|
||||
rated: 3,
|
||||
avatar:
|
||||
"https://www.gravatar.com/avatar/6529e885535ef67a3fad810ad71167c2c03f79480936e9b3a714731753cbb47e?d=robohash",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
module.exports = router
|
Loading…
Reference in New Issue
Block a user