All checks were successful
Auditor / audit (pull_request) Successful in 57s
- GET /tags returns deduplicated sorted array of all tags across todos - POST /todos/:id/tags attaches a tag to a todo (idempotent, ignores duplicates) - DELETE /todos/:id/tags/:tag removes a specific tag from a todo - Both /todos/:id/tags routes return 404 for non-existent todos
81 lines
1.9 KiB
JavaScript
81 lines
1.9 KiB
JavaScript
const express = require('express');
|
|
const { name, version } = require('./package.json');
|
|
|
|
const app = express();
|
|
const PORT = 3000;
|
|
|
|
app.use(express.json());
|
|
|
|
let todos = [
|
|
{ id: 1, title: 'Buy groceries', done: false, tags: [] },
|
|
{ id: 2, title: 'Walk the dog', done: true, tags: [] },
|
|
{ id: 3, title: 'Read a book', done: false, tags: [] },
|
|
];
|
|
|
|
let nextId = 4;
|
|
|
|
app.get('/healthz', (req, res) => {
|
|
res.json({ ok: true });
|
|
});
|
|
|
|
app.get('/version', (req, res) => {
|
|
res.json({ name, version });
|
|
});
|
|
|
|
app.get('/todos', (req, res) => {
|
|
const { tag } = req.query;
|
|
if (tag !== undefined) {
|
|
return res.json(todos.filter(t => t.tags.includes(tag)));
|
|
}
|
|
res.json(todos);
|
|
});
|
|
|
|
app.post('/todos', (req, res) => {
|
|
const { title, tags } = req.body;
|
|
const todo = { id: nextId++, title, done: false, tags: Array.isArray(tags) ? tags : [] };
|
|
todos.push(todo);
|
|
res.status(201).json(todo);
|
|
});
|
|
|
|
app.delete('/todos/:id', (req, res) => {
|
|
const id = parseInt(req.params.id, 10);
|
|
const index = todos.findIndex(t => t.id === id);
|
|
if (index === -1) {
|
|
return res.status(404).end();
|
|
}
|
|
todos.splice(index, 1);
|
|
res.status(204).end();
|
|
});
|
|
|
|
app.get('/tags', (req, res) => {
|
|
const tags = [...new Set(todos.flatMap(t => t.tags))].sort();
|
|
res.json(tags);
|
|
});
|
|
|
|
app.post('/todos/:id/tags', (req, res) => {
|
|
const id = parseInt(req.params.id, 10);
|
|
const todo = todos.find(t => t.id === id);
|
|
if (!todo) {
|
|
return res.status(404).end();
|
|
}
|
|
const { tag } = req.body;
|
|
if (!todo.tags.includes(tag)) {
|
|
todo.tags.push(tag);
|
|
}
|
|
res.json(todo);
|
|
});
|
|
|
|
app.delete('/todos/:id/tags/:tag', (req, res) => {
|
|
const id = parseInt(req.params.id, 10);
|
|
const todo = todos.find(t => t.id === id);
|
|
if (!todo) {
|
|
return res.status(404).end();
|
|
}
|
|
todo.tags = todo.tags.filter(t => t !== req.params.tag);
|
|
res.status(204).end();
|
|
});
|
|
|
|
app.listen(PORT, () => {
|
|
console.log(`Server listening on http://localhost:${PORT}`);
|
|
});
|