-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
378 lines (328 loc) · 10 KB
/
Copy pathindex.js
File metadata and controls
378 lines (328 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
const express = require('express');
const fs = require('fs');
const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
require('dotenv').config();
// Connects to Postgres using DATABASE_URL, creates the tasks table if
// missing, and seeds three example tasks only if the table is empty.
// Route bodies below still reference the old SQLite API for now — they
// get migrated to this repository in the next stages.
const repo = require('./db');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
// Sample tasks used only by POST /reset to restore the original three tasks.
const sampleTasks = [
{ title: 'Learn Express', done: false },
{ title: 'Build a CRUD API', done: false },
{ title: 'Read the assignment', done: true }
];
// Database-backed lookup + shaping, used by the migrated GET endpoints.
async function findTaskRow(taskId) {
const { rows } = await repo.pool.query('SELECT * FROM tasks WHERE id = $1', [Number(taskId)]);
return rows[0];
}
function toApiTask(row) {
return { id: row.id, title: row.title, done: row.done };
}
function notFoundResponse(res, taskId) {
return res.status(404).json({ error: `Task ${taskId} not found` });
}
/**
* @openapi
* /:
* get:
* summary: Describe the API
* responses:
* 200:
* description: API information
* /health:
* get:
* summary: Check API health
* responses:
* 200:
* description: The API is healthy
* /tasks:
* get:
* summary: List tasks with optional filtering, search, and pagination
* parameters:
* - in: query
* name: done
* schema: { type: boolean }
* description: Filter by completion status
* - in: query
* name: search
* schema: { type: string }
* description: Search titles case-insensitively
* - in: query
* name: limit
* schema: { type: integer, minimum: 0 }
* description: Maximum number of tasks to return
* - in: query
* name: offset
* schema: { type: integer, minimum: 0, default: 0 }
* description: Number of matching tasks to skip
* responses:
* 200:
* description: A list of tasks
* post:
* summary: Create a task
* requestBody:
* required: true
* content:
* application/json:
* schema: { $ref: '#/components/schemas/NewTask' }
* responses:
* 201: { description: Task created }
* 400: { description: Title is missing or empty }
* /tasks/{id}:
* get:
* summary: Get one task
* parameters:
* - $ref: '#/components/parameters/TaskId'
* responses:
* 200: { description: The requested task }
* 404: { description: Task not found }
* put:
* summary: Update a task
* parameters:
* - $ref: '#/components/parameters/TaskId'
* requestBody:
* required: true
* content:
* application/json:
* schema: { $ref: '#/components/schemas/TaskUpdate' }
* responses:
* 200: { description: Task updated }
* 400: { description: Empty or invalid body }
* 404: { description: Task not found }
* delete:
* summary: Delete a task
* parameters:
* - $ref: '#/components/parameters/TaskId'
* responses:
* 204: { description: Task deleted }
* 404: { description: Task not found }
* /stats:
* get:
* summary: Get task statistics
* responses:
* 200: { description: Total, done, and open task counts }
* /reset:
* post:
* summary: Restore the three sample tasks
* responses:
* 200: { description: Tasks restored }
* components:
* parameters:
* TaskId:
* name: id
* in: path
* required: true
* schema: { type: integer }
* description: Task id
* schemas:
* Task:
* type: object
* required: [id, title, done]
* properties:
* id: { type: integer, example: 1 }
* title: { type: string, example: Buy milk }
* done: { type: boolean, example: false }
* NewTask:
* type: object
* required: [title]
* properties:
* title: { type: string, example: Buy milk }
* TaskUpdate:
* type: object
* properties:
* title: { type: string, example: Buy oat milk }
* done: { type: boolean, example: true }
*/
const swaggerOptions = {
definition: {
openapi: '3.0.0',
info: {
title: 'Task API',
version: '1.0',
description: 'A Postgres-backed CRUD API for managing tasks.'
},
servers: [{ url: 'http://localhost:3000' }]
},
apis: [__filename]
};
const openapiDocument = swaggerJsdoc(swaggerOptions);
fs.writeFileSync('openapi.json', JSON.stringify(openapiDocument, null, 2));
app.use('/docs', swaggerUi.serve, swaggerUi.setup(openapiDocument));
app.get('/', (req, res) => {
res.json({
name: 'Task API',
version: '1.0',
endpoints: ['/tasks']
});
});
app.get('/health', async (req, res) => {
try {
await repo.ping();
res.json({ status: 'ok', db: 'ok' });
} catch (err) {
res.status(503).json({ status: 'ok', db: 'error' });
}
});
app.get('/tasks', async (req, res, next) => {
try {
const clauses = [];
const params = [];
if (req.query.done !== undefined) {
params.push(req.query.done === 'true');
clauses.push(`done = $${params.length}`);
}
if (req.query.search) {
params.push(`%${req.query.search}%`);
clauses.push(`title ILIKE $${params.length}`);
}
let sql = 'SELECT * FROM tasks';
if (clauses.length > 0) {
sql += ` WHERE ${clauses.join(' AND ')}`;
}
sql += ' ORDER BY id';
const offset = Number.parseInt(req.query.offset, 10) || 0;
const limit = Number.parseInt(req.query.limit, 10);
if (limit >= 0) {
params.push(limit);
sql += ` LIMIT $${params.length}`;
params.push(offset);
sql += ` OFFSET $${params.length}`;
} else if (offset > 0) {
params.push(offset);
sql += ` OFFSET $${params.length}`;
}
const { rows } = await repo.pool.query(sql, params);
res.json(rows.map(toApiTask));
} catch (err) {
next(err);
}
});
app.get('/tasks/:id', async (req, res, next) => {
try {
const task = await findTaskRow(req.params.id);
if (!task) {
return notFoundResponse(res, req.params.id);
}
res.json(toApiTask(task));
} catch (err) {
next(err);
}
});
app.post('/tasks', async (req, res, next) => {
try {
const { title } = req.body;
if (typeof title !== 'string') {
return res.status(400).json({ error: 'Title is required' });
}
if (title.trim() === '') {
return res.status(400).json({ error: 'Title cannot be empty' });
}
const { rows } = await repo.pool.query(
'INSERT INTO tasks (title, done) VALUES ($1, false) RETURNING *',
[title]
);
res.status(201).json(toApiTask(rows[0]));
} catch (err) {
next(err);
}
});
app.put('/tasks/:id', async (req, res, next) => {
try {
const task = await findTaskRow(req.params.id);
if (!task) {
return notFoundResponse(res, req.params.id);
}
const updates = req.body;
if (!updates || typeof updates !== 'object' || Array.isArray(updates)) {
return res.status(400).json({ error: 'Request body must include title or done' });
}
const hasTitle = Object.prototype.hasOwnProperty.call(updates, 'title');
const hasDone = Object.prototype.hasOwnProperty.call(updates, 'done');
if (!hasTitle && !hasDone) {
return res.status(400).json({ error: 'Request body must include title or done' });
}
if (hasTitle && (typeof updates.title !== 'string' || updates.title.trim() === '')) {
return res.status(400).json({ error: 'Title must be a non-empty string' });
}
if (hasDone && typeof updates.done !== 'boolean') {
return res.status(400).json({ error: 'Done must be a boolean' });
}
const nextTitle = hasTitle ? updates.title : task.title;
const nextDone = hasDone ? updates.done : task.done;
const { rows } = await repo.pool.query(
'UPDATE tasks SET title = $1, done = $2 WHERE id = $3 RETURNING *',
[nextTitle, nextDone, task.id]
);
res.json(toApiTask(rows[0]));
} catch (err) {
next(err);
}
});
app.delete('/tasks/:id', async (req, res, next) => {
try {
const task = await findTaskRow(req.params.id);
if (!task) {
return notFoundResponse(res, req.params.id);
}
await repo.pool.query('DELETE FROM tasks WHERE id = $1', [task.id]);
res.status(204).send();
} catch (err) {
next(err);
}
});
app.get('/stats', async (req, res, next) => {
try {
const { rows } = await repo.pool.query(
"SELECT COUNT(*)::int AS total, COUNT(*) FILTER (WHERE done)::int AS done FROM tasks"
);
const { total, done } = rows[0];
res.json({ total, done, open: total - done });
} catch (err) {
next(err);
}
});
app.post('/reset', async (req, res, next) => {
try {
const client = await repo.pool.connect();
try {
await client.query('BEGIN');
await client.query('DELETE FROM tasks');
await client.query('ALTER SEQUENCE tasks_id_seq RESTART WITH 1');
for (const task of sampleTasks) {
await client.query('INSERT INTO tasks (title, done) VALUES ($1, $2)', [task.title, task.done]);
}
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
const { rows } = await repo.pool.query('SELECT * FROM tasks ORDER BY id');
res.json(rows.map(toApiTask));
} catch (err) {
next(err);
}
});
repo.init()
.then(() => {
app.listen(PORT, () => {
console.log(`Task API running at http://localhost:${PORT}`);
});
})
.catch((err) => {
console.error('Failed to initialize the database', err);
process.exit(1);
});
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: 'Internal server error' });
});