This repository has been archived by the owner on Sep 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path[id].ts
71 lines (66 loc) · 2.33 KB
/
[id].ts
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
import { NextApiRequest, NextApiResponse } from 'next';
import { TodoItem } from '../../../db/models/todoItems';
import tigrisDb from '../../../lib/tigris';
type Data = {
result?: TodoItem;
error?: string;
};
// GET /api/item/[id] -- gets item from collection where id = [id]
// PUT /api/item/[id] {ToDoItem} -- updates the item in collection where id = [id]
// DELETE /api/item/[id] -- deletes the item in collection where id = [id]
export default async function handler(req: NextApiRequest, res: NextApiResponse<Data>) {
const { id } = req.query;
switch (req.method) {
case 'GET':
await handleGet(req, res, Number(id));
break;
case 'PUT':
await handlePut(req, res);
break;
case 'DELETE':
await handleDelete(req, res, Number(id));
break;
default:
res.setHeader('Allow', ['GET', 'PUT', 'DELETE']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
async function handleGet(req: NextApiRequest, res: NextApiResponse<Data>, itemId: number) {
try {
const itemsCollection = tigrisDb.getCollection<TodoItem>(TodoItem);
const item = await itemsCollection.findOne({ filter: { id: itemId } });
if (!item) {
res.status(404).json({ error: 'No item found' });
} else {
res.status(200).json({ result: item });
}
} catch (err) {
const error = err as Error;
res.status(500).json({ error: error.message });
}
}
async function handlePut(req: NextApiRequest, res: NextApiResponse<Data>) {
try {
const item = JSON.parse(req.body) as TodoItem;
const itemsCollection = tigrisDb.getCollection<TodoItem>(TodoItem);
const updated = await itemsCollection.insertOrReplaceOne(item);
res.status(200).json({ result: updated });
} catch (err) {
const error = err as Error;
res.status(500).json({ error: error.message });
}
}
async function handleDelete(req: NextApiRequest, res: NextApiResponse<Data>, itemId: number) {
try {
const itemsCollection = tigrisDb.getCollection<TodoItem>(TodoItem);
const status = (await itemsCollection.deleteOne({ filter: { id: itemId } })).status;
if (status === 'deleted') {
res.status(200).json({});
} else {
res.status(500).json({ error: `Failed to delete ${itemId}` });
}
} catch (err) {
const error = err as Error;
res.status(500).json({ error: error.message });
}
}