Загрузка данных
const http = require('http');
const url = require('url');
// Хранилище задач (в памяти)
let tasks = [];
let nextId = 1;
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const path = parsedUrl.pathname;
const method = req.method;
const query = parsedUrl.query; // объект с query-параметрами
// Установка заголовков
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (method === 'OPTIONS') {
res.writeHead(204);
res.end();
return;
}
// Маршрут GET /tasks (с опциональным query-параметром id)
if (path === '/tasks' && method === 'GET') {
if (query.id) {
// Получение одной задачи по id
const id = parseInt(query.id);
if (isNaN(id)) {
res.writeHead(400);
res.end(JSON.stringify({ error: 'Некорректный id' }));
return;
}
const task = tasks.find(t => t.id === id);
if (!task) {
res.writeHead(404);
res.end(JSON.stringify({ error: 'Задача не найдена' }));
return;
}
res.writeHead(200);
res.end(JSON.stringify(task));
} else {
// Получение всех задач
res.writeHead(200);
res.end(JSON.stringify(tasks));
}
}
// POST /tasks – создание задачи
else if (path === '/tasks' && method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
const { title, description, completed = false } = JSON.parse(body);
if (!title || !description) {
throw new Error('Поля title и description обязательны');
}
const newTask = {
id: nextId++,
title,
description,
completed
};
tasks.push(newTask);
res.writeHead(201);
res.end(JSON.stringify(newTask));
} catch (error) {
res.writeHead(400);
res.end(JSON.stringify({ error: error.message }));
}
});
}
// PUT /tasks/:id – обновление задачи
else if (path.startsWith('/tasks/') && method === 'PUT') {
const id = parseInt(path.split('/')[2]);
if (isNaN(id)) {
res.writeHead(400);
res.end(JSON.stringify({ error: 'Некорректный id' }));
return;
}
const taskIndex = tasks.findIndex(t => t.id === id);
if (taskIndex === -1) {
res.writeHead(404);
res.end(JSON.stringify({ error: 'Задача не найдена' }));
return;
}
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
const updates = JSON.parse(body);
delete updates.id; // запрещаем изменение id
tasks[taskIndex] = { ...tasks[taskIndex], ...updates };
res.writeHead(200);
res.end(JSON.stringify(tasks[taskIndex]));
} catch (error) {
res.writeHead(400);
res.end(JSON.stringify({ error: 'Некорректный JSON' }));
}
});
}
// DELETE /tasks/:id – удаление задачи
else if (path.startsWith('/tasks/') && method === 'DELETE') {
const id = parseInt(path.split('/')[2]);
if (isNaN(id)) {
res.writeHead(400);
res.end(JSON.stringify({ error: 'Некорректный id' }));
return;
}
const taskIndex = tasks.findIndex(t => t.id === id);
if (taskIndex === -1) {
res.writeHead(404);
res.end(JSON.stringify({ error: 'Задача не найдена' }));
return;
}
tasks.splice(taskIndex, 1);
res.writeHead(204);
res.end();
}
// Неизвестный маршрут
else {
res.writeHead(404);
res.end(JSON.stringify({ error: 'Маршрут не найден' }));
}
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Сервер запущен на порту ${PORT}`);
});