-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.api.ts
52 lines (40 loc) · 1.1 KB
/
handler.api.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
import { createApp, createRouter, defineEventHandler } from "vinxi/http";
import { ITEMS as POSTS, sleep } from "./common";
const app = createApp();
const postsRouter = createRouter();
postsRouter.get(
"/posts",
defineEventHandler(async () => {
await sleep(750);
const posts = POSTS.map((invoice) => ({
id: invoice.id,
title: invoice.title.replace("--item--", "Post"),
}));
return new Response(JSON.stringify(posts), {
status: 200,
headers: { "Content-Type": "application/json" },
});
})
);
const postIdRouter = createRouter();
postIdRouter.get(
"/posts/:id",
defineEventHandler(async (event) => {
await sleep(250);
const postId = event.context.params.id;
const post = POSTS.find((p) => p.id === postId);
if (!post) {
return new Response(`A post with an ID of "${postId}" was not found.`, {
status: 404,
});
}
post.title = post.title.replace("--item--", "Post");
return new Response(JSON.stringify(post), {
status: 200,
headers: { "Content-Type": "application/json" },
});
})
);
app.use(postsRouter);
app.use(postIdRouter);
export default app.handler;