feat: kfu-m-24-1/eng-it-lean add /users endpoint; small features in /units #85
@ -1,8 +1,10 @@
|
||||
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 =
|
||||
@ -12,6 +14,8 @@ 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);
|
||||
|
@ -4,9 +4,45 @@ const router = require('express').Router();
|
||||
|
||||
module.exports = router;
|
||||
|
||||
const data = require('./data/units.json');
|
||||
const data = require('./units.json');
|
||||
const users = require('../users/users.json');
|
||||
router.get('/', (req, res) => {
|
||||
res.send(data);
|
||||
// for every data set author from users and save it to authoredData variable
|
||||
const authoredData = data.map((unit) => {
|
||||
const user = users.find((user) => user.public_id == unit.author);
|
||||
if (user) {
|
||||
unit.author = user;
|
||||
}
|
||||
return unit;
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
fs.writeFileSync(path.join(__dirname, 'units.json'), JSON.stringify(data));
|
||||
res.status(200).send(data);
|
||||
});
|
||||
|
||||
router.put('/', (req, res) => {
|
||||
@ -16,17 +52,21 @@ 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;
|
||||
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({ ...unit, id: newId });
|
||||
|
||||
fs.writeFileSync(path.join(__dirname, 'data', 'units.json'), JSON.stringify(data));
|
||||
fs.writeFileSync(path.join(__dirname, 'units.json'), JSON.stringify(data));
|
||||
res.status(200).send(data);
|
||||
});
|
||||
|
||||
@ -39,7 +79,7 @@ router.delete('/:id', (req, res) => {
|
||||
}
|
||||
|
||||
data.splice(index, 1);
|
||||
fs.writeFileSync(path.join(__dirname, 'data', 'units.json'), JSON.stringify(data));
|
||||
fs.writeFileSync(path.join(__dirname, 'units.json'), JSON.stringify(data));
|
||||
res.send({ message: `Unit with ID ${id} deleted` });
|
||||
});
|
||||
|
||||
@ -48,15 +88,17 @@ router.get('/:id', (req, res) => {
|
||||
const unit = data.find((unit) => unit.id === id);
|
||||
|
||||
if (!unit) {
|
||||
return res.status(404).send('Not found');
|
||||
return res.status(404).send('Unit not found');
|
||||
}
|
||||
|
||||
const unitFilepath = path.join(__dirname, 'data', `${unit.filename}.md`);
|
||||
const unitContent = fs.readFileSync(unitFilepath, 'utf-8');
|
||||
|
||||
if (!unitContent) {
|
||||
return res.status(404).send('Not found');
|
||||
const user = users.find((user) => {
|
||||
if (user.public_id == unit.author) {
|
||||
return user;
|
||||
}
|
||||
});
|
||||
if (!user) {
|
||||
return res.status(404).send('User not found');
|
||||
}
|
||||
|
||||
res.send({ ...unit, content: unitContent });
|
||||
res.send({...unit, author: user});
|
||||
});
|
||||
|
20
server/routers/kfu-m-24-1/eng-it-lean/units/units.json
Normal file
20
server/routers/kfu-m-24-1/eng-it-lean/units/units.json
Normal file
@ -0,0 +1,20 @@
|
||||
[
|
||||
{
|
||||
"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"
|
||||
}
|
||||
]
|
68
server/routers/kfu-m-24-1/eng-it-lean/users/index.js
Normal file
68
server/routers/kfu-m-24-1/eng-it-lean/users/index.js
Normal file
@ -0,0 +1,68 @@
|
||||
const router = require('express').Router();
|
||||
const fs = require('fs');
|
||||
|
||||
module.exports = router;
|
||||
|
||||
const data = require('./users.json');
|
||||
const path = require('path');
|
||||
router.get('/', (req, res) => {
|
||||
res.send(data);
|
||||
});
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
const newUser = req.body;
|
||||
const updatedData = [...data, newUser];
|
||||
|
||||
console.log(updatedData);
|
||||
|
||||
fs.writeFile(path.join(__dirname, 'users.json'), JSON.stringify(updatedData), (err) => {
|
||||
if (err) {
|
||||
console.error('Ошибка при записи данных в файл users.json', err);
|
||||
res.status(500).send('Ошибка при записи данных в файл users.json');
|
||||
} else {
|
||||
console.log('Данные успешно записаны в файл users.json');
|
||||
res.status(200).send('Данные успешно записаны в файл users.json');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
router.post('/login', (req, res) => {
|
||||
const { email, password } = req.body;
|
||||
console.log(email);
|
||||
console.log(req.body);
|
||||
const user = data.find((user) => user.email === email && user.password === password);
|
||||
console.log(user);
|
||||
|
||||
if (!user) {
|
||||
res.status(404).send('Пользователь не найден');
|
||||
}
|
||||
res.json({ public_id: user.public_id });
|
||||
});
|
||||
|
||||
router.get('/account', (req, res) => {
|
||||
const { public_id } = req.query;
|
||||
console.log(public_id);
|
||||
const user = data.find((user) => user.public_id == public_id);
|
||||
|
||||
if (!user) {
|
||||
res.status(404).send('Пользователь не найден');
|
||||
}
|
||||
console.log(user);
|
||||
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
server/routers/kfu-m-24-1/eng-it-lean/users/users.json
Normal file
1
server/routers/kfu-m-24-1/eng-it-lean/users/users.json
Normal file
@ -0,0 +1 @@
|
||||
[{"id":1738707541324,"public_id":1738707541324,"email":"1@gmail.com","password":"1","age":"22","nickname":"324324","about":"Чиловый "}]
|
Loading…
Reference in New Issue
Block a user