From 68de877b068e8d97c053c369b46e6335571cea89 Mon Sep 17 00:00:00 2001 From: Ruslan Zagitov Date: Fri, 31 Jan 2025 13:59:40 +0300 Subject: [PATCH] refactor: /dictionaries endpoint --- .../dictionaries/data/dictionaries.json | 17 --- .../dictionaries/data/dictionaryWords.json | 133 +---------------- .../dictionaries/dictionaries.json | 1 + .../eng-it-lean/dictionaries/index.js | 114 ++++++++++----- .../kfu-m-24-1/eng-it-lean/units/index.js | 6 +- .../kfu-m-24-1/eng-it-lean/words/index.js | 75 ++++++++++ .../kfu-m-24-1/eng-it-lean/words/words.json | 136 ++++++++++++++++++ 7 files changed, 297 insertions(+), 185 deletions(-) delete mode 100644 server/routers/kfu-m-24-1/eng-it-lean/dictionaries/data/dictionaries.json create mode 100644 server/routers/kfu-m-24-1/eng-it-lean/dictionaries/dictionaries.json create mode 100644 server/routers/kfu-m-24-1/eng-it-lean/words/index.js create mode 100644 server/routers/kfu-m-24-1/eng-it-lean/words/words.json diff --git a/server/routers/kfu-m-24-1/eng-it-lean/dictionaries/data/dictionaries.json b/server/routers/kfu-m-24-1/eng-it-lean/dictionaries/data/dictionaries.json deleted file mode 100644 index d0e301c..0000000 --- a/server/routers/kfu-m-24-1/eng-it-lean/dictionaries/data/dictionaries.json +++ /dev/null @@ -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" - } -] diff --git a/server/routers/kfu-m-24-1/eng-it-lean/dictionaries/data/dictionaryWords.json b/server/routers/kfu-m-24-1/eng-it-lean/dictionaries/data/dictionaryWords.json index b7a698d..42c590a 100644 --- a/server/routers/kfu-m-24-1/eng-it-lean/dictionaries/data/dictionaryWords.json +++ b/server/routers/kfu-m-24-1/eng-it-lean/dictionaries/data/dictionaryWords.json @@ -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." - ] - } - ] } ] diff --git a/server/routers/kfu-m-24-1/eng-it-lean/dictionaries/dictionaries.json b/server/routers/kfu-m-24-1/eng-it-lean/dictionaries/dictionaries.json new file mode 100644 index 0000000..d2641c8 --- /dev/null +++ b/server/routers/kfu-m-24-1/eng-it-lean/dictionaries/dictionaries.json @@ -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]}] \ No newline at end of file diff --git a/server/routers/kfu-m-24-1/eng-it-lean/dictionaries/index.js b/server/routers/kfu-m-24-1/eng-it-lean/dictionaries/index.js index c203e4b..f25901b 100644 --- a/server/routers/kfu-m-24-1/eng-it-lean/dictionaries/index.js +++ b/server/routers/kfu-m-24-1/eng-it-lean/dictionaries/index.js @@ -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); -}); diff --git a/server/routers/kfu-m-24-1/eng-it-lean/units/index.js b/server/routers/kfu-m-24-1/eng-it-lean/units/index.js index 4824386..4eff2ce 100644 --- a/server/routers/kfu-m-24-1/eng-it-lean/units/index.js +++ b/server/routers/kfu-m-24-1/eng-it-lean/units/index.js @@ -21,10 +21,10 @@ router.put('/', (req, res) => { } const newId = data.length + 1; - const fileName = newUnit.name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); - fs.writeFileSync(path.join(__dirname, 'data', `${fileName}.md`), newUnit.content); + 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 }); + 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); diff --git a/server/routers/kfu-m-24-1/eng-it-lean/words/index.js b/server/routers/kfu-m-24-1/eng-it-lean/words/index.js new file mode 100644 index 0000000..fdec2ac --- /dev/null +++ b/server/routers/kfu-m-24-1/eng-it-lean/words/index.js @@ -0,0 +1,75 @@ +const fs = require('fs'); +const path = require('path'); +const router = require("express").Router(); + +module.exports = router; + +const words = require("../words/words.json"); + +router.get("/", (req, res) => { + res.send(words); +}); + +router.put('/', (req, res) => { + const newData = req.body; + if (!newData) { + return res.status(400).send('No data to add'); // Bad request + } + if (!words) { + return res.status(500).send('No data to update'); // Internal server error + } + console.log(words.length) + const indexedUpdatedData = { ...newData, id: words.length + 1 }; // Add the new word to the array + console.log(indexedUpdatedData); + words.push(indexedUpdatedData); // Add the new word to the array + fs.writeFile(path.join(__dirname, 'words.json'), JSON.stringify(words), (err) => { + if (err) { + console.error(err); // Log the error + return res.status(500).send('Error saving data'); + } + res.status(200).json(indexedUpdatedData); + }); +}); + +router.get("/:id", (req, res) => { + const id = parseInt(req.params.id); + + if (!id || isNaN(id)) { + return res.status(400).send('Invalid ID'); // Bad request + } + + if (!words) { + return res.status(500).send('No data to update'); // Internal server error + } + const word = words.find((word) => word.id === id); + + if (!word) { + return res.status(404).send("Not found"); + } + res.send(word); +}); + +router.delete("/:id", (req, res) => { + const id = parseInt(req.params.id); + if (!id || isNaN(id)) { + return res.status(400).send('Invalid ID'); // Bad request + } + + const index = words.findIndex((word) => word.id === id); + if (index < 0) { + return res.status(404).send("Not found"); + } + + if (!words) { + return res.status(500).send('No data to update'); // Internal server error + } + + words.splice(index, 1); + fs.writeFile(path.join(__dirname, 'words.json'), JSON.stringify(words), (err) => { + if (err) { + console.error(err); // Log the error + return res.status(500).send('Error saving data'); + } + res.send({ message: `Word with id ${id} deleted` }); + }); +}); \ No newline at end of file diff --git a/server/routers/kfu-m-24-1/eng-it-lean/words/words.json b/server/routers/kfu-m-24-1/eng-it-lean/words/words.json new file mode 100644 index 0000000..7c08b69 --- /dev/null +++ b/server/routers/kfu-m-24-1/eng-it-lean/words/words.json @@ -0,0 +1,136 @@ +[ + { + "id": 12, + "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.”"], + "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.”"], + "synonyms": [] + }, + { + "id": 2, + "word": "Machine Learning", + "translation": "Машинное обучение", + "definition": "An approach to artificial intelligence where computers learn from data without being explicitly programmed.", + "synonyms": ["Trainable Algorithms", "Automated Learning"], + "examples": [ + "We used machine learning techniques to forecast product demand.", + "The movie recommendation system is based on machine learning algorithms.", + "Machine learning helped improve the accuracy of speech recognition in our application." + ] + }, + { + "id": 3, + "word": "Neural Network", + "translation": "Нейронная сеть", + "definition": "A mathematical model inspired by the structure and function of biological neural networks, consisting of interconnected nodes organized in layers that can process information.", + "synonyms": ["Artificial Neural Network", "Deep Neural Network"], + "examples": [ + "To process large amounts of data, we created a deep learning neural network.", + "This neural network is capable of generating realistic images.", + "Using neural networks significantly improved the quality of text translation." + ] + }, + { + "id": 4, + "word": "Algorithm", + "translation": "Алгоритм", + "definition": "A step-by-step procedure or set of instructions for solving a problem or performing a computation.", + "synonyms": ["Procedure", "Method"], + "examples": [ + "The algorithm we developed quickly finds the optimal delivery route.", + "This algorithm sorts an array with a minimal number of operations.", + "Encryption algorithms ensure secure transmission of data over the internet." + ] + }, + { + "id": 5, + "word": "Data Model", + "translation": "Модель данных", + "definition": "An abstract representation of the structure of data, describing how data is organized and related to each other.", + "synonyms": ["Data Structure", "Schema"], + "examples": [ + "Our data model allows us to efficiently manage relationships between customers and orders.", + "The data model was designed considering scalability and performance requirements.", + "This data model is used for storing information about social network users." + ] + }, + { + "id": 6, + "word": "Regression", + "translation": "Регрессия", + "definition": "A statistical method used to determine the relationship between one variable and others.", + "synonyms": ["Linear Regression", "Nonlinear Regression"], + "examples": [ + "We applied linear regression to analyze the impact of advertising campaigns on sales.", + "Results from the regression analysis showed a strong correlation between customer age and purchase frequency.", + "Regression helped us assess how changes in environmental conditions affect crop yield." + ] + }, + { + "id": 7, + "word": "Clustering", + "translation": "Кластеризация", + "definition": "The process of grouping similar objects into clusters so that objects within the same cluster are more similar to each other than to those in other clusters.", + "synonyms": ["Grouping", "Segmentation"], + "examples": [ + "Clustering allowed us to divide customers into several groups according to their purchasing behavior.", + "Clustering methods are used to automatically group news by topic.", + "As a result of clustering, several market segments were identified, each with its own characteristics." + ] + }, + { + "id": 8, + "word": "Supervised Learning", + "translation": "Обучение с учителем", + "definition": "A type of machine learning where the algorithm learns from labeled data, meaning data for which correct answers are known.", + "synonyms": ["Controlled Learning", "Labeled Classification"], + "examples": [ + "Supervised learning is used to classify emails as spam or not-spam.", + "This approach was used to create a model that predicts real estate prices based on multiple parameters.", + "Supervised learning helps diagnose diseases at early stages through medical data analysis." + ] + }, + { + "id": 9, + "word": "Data Labeling", + "translation": "Разметка данных", + "definition": "The process of assigning labels or classes to data so it can be used in supervised learning.", + "synonyms": ["Data Annotation", "Tagging"], + "examples": [ + "Before starting model training, we labeled the data by assigning each photo an animal category.", + "Data labeling includes marking user reviews as positive or negative.", + "Text documents were labeled with special tags for subsequent analysis." + ] + }, + { + "id": 10, + "word": "Hyperparameters", + "translation": "Гиперпараметры", + "definition": "Parameters that define the structure and behavior of a machine learning model, set before the learning process begins.", + "synonyms": ["Model Settings", "Configuration Parameters"], + "examples": [ + "Optimizing hyperparameters enabled us to enhance the performance of our machine learning model.", + "Hyperparameters include settings such as the number of layers in a neural network and the learning rate.", + "Choosing the right hyperparameters is crucial for achieving high model accuracy." + ] + }, + { + "id": 11, + "word": "Model Validation", + "translation": "Валидация модели", + "definition": "The process of evaluating the quality of a model by testing it on new, previously unseen data.", + "synonyms": ["Model Testing", "Model Verification"], + "examples": [ + "After completing the training, we validated the model using a test dataset.", + "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." + ] + } +]