refactor: /dictionaries endpoint

This commit is contained in:
Ruslan Zagitov
2025-01-31 13:59:40 +03:00
parent daf5bf7970
commit 68de877b06
7 changed files with 297 additions and 185 deletions

View File

@@ -1,17 +0,0 @@
[
{
"id": 0,
"description": "10 часто используемых",
"imageFilename": "kart1.jpg"
},
{
"id": 1,
"description": "10 слов в Data Science",
"imageFilename": "kart1.jpg"
},
{
"id": 2,
"description": "IT Basics Dictionary",
"imageFilename": "kart1.jpg"
}
]

View File

@@ -6,18 +6,14 @@
"id": 0,
"word": "Tech",
"definition": "short for technical, relating to the knowledge, machines, or methods used in science and industry. Tech is a whole industry, which includes IT",
"examples": [
"“As a DevOps engineer I have been working in Tech since 2020.”"
],
"examples": ["“As a DevOps engineer I have been working in Tech since 2020.”"],
"synonyms": ["IT"]
},
{
"id": 1,
"word": "career path",
"definition": "the series of jobs or roles that constitute a person's career, especially one in a particular field",
"examples": [
"“Technology is an evolving field with a variety of available career paths.”"
],
"examples": ["“Technology is an evolving field with a variety of available career paths.”"],
"synonyms": []
}
]
@@ -146,130 +142,5 @@
]
}
]
},
{
"id": 2,
"words": [
{
"id": 0,
"word": "software",
"translation": "программное обеспечение",
"definition": "A collection of computer instructions that perform a specific task, typically for use by humans or machines.",
"synonyms": ["код", "приложение", "управление программами"],
"examples":
[
"I need to update the software on my new laptop.",
"The company uses Windows as its operating system."
]
},
{
"id": 1,
"word": "hardware",
"translation": "железо",
"definition": "Physical components of a computer that process information, including processors and storage devices.",
"synonyms": ["equipment", "приборы", "оборудование"],
"examples":
[
"The keyboard is part of the hardware on this device.",
"They upgraded their router to improve internet speed."
]
},
{
"id": 2,
"word": "network",
"translation": "сети",
"definition": "A system of interconnected devices that communicate with each other through data transmission over a networked medium.",
"synonyms": ["трансляция", "коммуникации", "диалог"],
"examples":
[
"We use the internet to connect our devices in the same area.",
"The company relies on their internal network for data sharing."
]
},
{
"id": 3,
"word": "algorithm",
"translation": "алгоритм",
"definition": "A set of instructions that a computer follows to solve a problem or achieve a specific task.",
"synonyms": ["процесс", "схема", "текст"],
"examples":
[
"The algorithm for sorting numbers is easy to follow.",
"The new software includes an advanced algorithm."
]
},
{
"id": 4,
"word": "encryption",
"translation": "криптография",
"definition": "A technique that transforms information into a secure form, making it unreadable without the appropriate key.",
"synonyms": ["шифрование", "окрышение", "опциональное"],
"examples":
[
"Our data is encrypted to ensure its privacy and security.",
"I need to use an encryption program for my important documents."
]
},
{
"id": 5,
"word": "debugging",
"translation": "поиск и исправление ошибок",
"definition": "The process of identifying and correcting errors or defects in a computer program.",
"synonyms": ["исправление", "сканирование", "анализ"],
"examples":
[
"I need to debug the code for this new project.",
"We use automated tools to find bugs."
]
},
{
"id": 6,
"word": "API",
"translation": "интерфейс приложения",
"definition": "A set of rules and protocols that enables communication between software applications, typically over a network.",
"synonyms": ["серверное программирование", "функциональная структура"],
"examples":
[
"We use the API for our mobile app to access data from the backend server.",
"I need to write an API for connecting my devices to the internet."
]
},
{
"id": 7,
"word": "virtual",
"translation": "виртуальный",
"definition": "A representation of a thing that does not exist physically but exists in digital form.",
"synonyms": ["высокопроизводительный", "представление", "цифровой"],
"examples":
[
"I use virtual reality to experience different environments.",
"Our company offers virtual office spaces for remote work."
]
},
{
"id": 8,
"word": "infrastructure",
"translation": "инфраструктура",
"definition": "The underlying systems and equipment of a computer network or organization, including hardware, software, and physical connections.",
"synonyms": ["оборудование", "устройство", "системы"],
"examples":
[
"Our IT infrastructure is robust to ensure reliable operations.",
"They need to improve their internet infrastructure for better connectivity."
]
},
{
"id": 9,
"word": "hacker",
"translation": "хакер",
"definition": "A skilled individual who uses computer technology to break into and misuse a system or network.",
"synonyms": ["дезориентированный", "манипулятор", "прокурор"],
"examples":
[
"I need to avoid getting involved with hackers.",
"They were caught hacking into the company's confidential database."
]
}
]
}
]

View File

@@ -0,0 +1 @@
[{"id":1,"description":"1000 часто используемых","imageFilename":"kart1.jpg","words":[0,1]},{"id":2,"description":"10 слов в Data Science","imageFilename":"kart1.jpg","words":[2,3,4,5,6,7,8,9,10,11,12]}]

View File

@@ -1,42 +1,99 @@
const fs = require('fs');
const path = require('path');
const router = require("express").Router();
const router = require('express').Router();
module.exports = router;
const data = require("./data/dictionaries.json");
const wordsData = require("./data/dictionaryWords.json");
const dictionaries = require('./dictionaries.json');
const words = require('../words/words.json');
router.get("/", (req, res) => {
res.send(data);
router.get('/', (req, res) => {
res.send(dictionaries);
});
// Put new dictionary to the array of dictionaries
router.put('/new', (req, res) => {
if (!data || !Array.isArray(data)) {
return res.status(400).send('No array of dictionaries found`');
router.get('/:id', (req, res) => {
const id = parseInt(req.params.id);
if (!id || isNaN(id)) {
return res.status(400).send('Invalid ID'); // Bad request
}
const updatedData = req.body;
if (!updatedData) {
return res.status(400).send('No data to update'); // Bad request
}
if (!data) {
if (!dictionaries) {
return res.status(500).send('No data to update'); // Internal server error
}
indexedUpdatedData = { id: data.length, ...updatedData }; // Add the new dictionary to the array
const dictionary = dictionaries.find((dictionary) => dictionary.id === id);
data.push(indexedUpdatedData); // Add the new dictionary to the array
if (!dictionary) {
return res.status(404).send('Not found');
}
const dictionaryWords = dictionary.words.map((wordId) => {
const word = words.find((word) => word.id === wordId);
return { ...word, ...word };
});
res.send({ ...dictionary, words: dictionaryWords });
});
fs.writeFile(path.join(__dirname, 'data/dictionaries.json'), JSON.stringify(data), (err) => {
router.post('/:id', (req, res) => {
const id = parseInt(req.params.id);
if (!id || isNaN(id)) {
return res.status(400).send('Invalid ID'); // Bad request
}
if (!dictionaries) {
return res.status(500).send('No data to update'); // Internal server error
}
const dictionary = dictionaries.find((dictionary) => dictionary.id === id);
if (!dictionary) {
return res.status(404).send('Not found');
}
const newWord = req.body;
if (!newWord) {
return res.status(400).send('No data to add'); // Bad request
}
console.log(newWord);
if (isNaN(newWord.id)) {
return res.status(400).send('Invalid word ID'); // Bad request
}
dictionary.words.push(newWord.id);
fs.writeFile(path.join(__dirname, 'dictionaries.json'), JSON.stringify(dictionaries), (err) => {
if (err) {
console.error(err); // Log the error
return res.status(500).send('Error saving data');
}
res.status(200).json(data); // Send back the updated data
res.status(200).json(dictionary); // Send back the updated data
});
});
// Put new dictionary to the array of dictionaries
router.put('/', (req, res) => {
if (!dictionaries || !Array.isArray(dictionaries)) {
return res.status(400).send('No array of dictionaries found`');
}
const newData = req.body;
if (!newData) {
return res.status(400).send('No data to add'); // Bad request
}
if (!dictionaries) {
return res.status(500).send('No data to update'); // Internal server error
}
const indexedUpdatedData = { ...newData, id: dictionaries.length + 1 }; // Add the new dictionary to the array
dictionaries.push(indexedUpdatedData); // Add the new dictionary to the array
fs.writeFile(path.join(__dirname, 'dictionaries.json'), JSON.stringify(dictionaries), (err) => {
if (err) {
console.error(err); // Log the error
return res.status(500).send('Error saving data');
}
res.status(200).json(dictionaries); // Send back the updated data
});
});
@@ -47,15 +104,15 @@ router.delete('/:id', (req, res) => {
return res.status(400).send('Invalid ID'); // Bad request
}
const index = data.findIndex((dictionary) => dictionary.id === id);
const index = dictionaries.findIndex((dictionary) => dictionary.id === id);
if (index < 0) {
return res.status(404).send('Not found'); // Not found
}
data.splice(index, 1); // Remove the dictionary from the array
dictionaries.splice(index, 1); // Remove the dictionary from the array
fs.writeFile(path.join(__dirname, 'data/dictionaries.json'), JSON.stringify(data), (err) => {
fs.writeFile(path.join(__dirname, 'dictionaries.json'), JSON.stringify(dictionaries), (err) => {
if (err) {
console.error(err); // Log the error
return res.status(500).send('Error saving data');
@@ -63,14 +120,3 @@ router.delete('/:id', (req, res) => {
res.send({ message: `Dictionary with id ${id} deleted` });
});
});
router.get("/:id", (req, res) => {
const id = parseInt(req.params.id);
const words = wordsData.find((word) => word.id === id);
if (!words) {
return res.status(404).send("Not found");
}
res.send(words);
});