-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path[id].tsx
More file actions
49 lines (44 loc) · 1.21 KB
/
Copy path[id].tsx
File metadata and controls
49 lines (44 loc) · 1.21 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
import { NextApiHandler, NextApiRequest, NextApiResponse } from "next";
import { allBlogs, getSlug, updateBlogFile } from "src/cms/blogs/utils";
import { BlogStatus } from "src/enums/BlogStatus";
const find = async (req, res) => {
const { id } = req.query;
const blogs = allBlogs();
const blog = blogs.find((blog) => String(blog.id) === String(id));
if (!blog) {
res.statusCode = 404;
res.end();
} else {
res.statusCode = 200;
res.end(JSON.stringify(blog));
}
};
const update = async (req: NextApiRequest, res: NextApiResponse) => {
try {
const { id } = req.query;
const payload = {
...req.body,
updatedAt: new Date().toISOString(),
slug: getSlug(req.body.title),
status: BlogStatus[req.body.status],
};
const result = await updateBlogFile(payload, String(id));
if (!result) throw new Error("Failed to update file");
res.statusCode = 200;
res.end(JSON.stringify(payload));
} catch (error) {
res.statusCode = 404;
res.end();
}
};
const handler: NextApiHandler = async (req, res) => {
switch (req.method) {
case "PUT":
update(req, res);
break;
default:
find(req, res);
break;
}
};
export default handler;