-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
111 lines (93 loc) · 2.93 KB
/
index.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
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
import { serve } from "bun";
import figlet from "figlet";
const PORT = 3049;
interface Post{
id: string;
title: string;
content: string;
}
let blogPosts: Post[] = [];
function handleGetAllPosts(){
return new Response(JSON.stringify(blogPosts), {
headers: {
"Content-Type": "application/json"
}
});
}
function handleGetPostById(id: string){
const post = blogPosts.find((post) => post.id == id);
if (post){
return new Response(JSON.stringify(post), {
headers: {
"Content-Type": "application/json"
}
});
}else{
return new Response('Not Found', {status: 404});
}
}
function handleCreatePost(title: string, content: string){
const newPost: Post = {
id: `${blogPosts.length }`,
title,
content,
}
blogPosts.push(newPost);
return new Response(JSON.stringify(newPost), {
headers: {"Content-Type": "application/json"},
status: 201,
});
}
function handleUpdatePost(id: string, title: string, content: string){
const postIndex = blogPosts.findIndex((post) => post.id == id);
if (postIndex === -1){
return new Response('Not Found', {status: 404});
}
blogPosts[postIndex] = {
...blogPosts[postIndex],
title,
content,
}
return new Response('Post Updated', {status: 200});
}
function handleDeletePost(id: string){
const postIndex = blogPosts.findIndex((post) => post.id == id);
if (postIndex === -1){
return new Response('Not Found', {status: 404});
}
blogPosts.splice(postIndex, 1);
return new Response('Post Deleted', {status: 200});
}
serve({
port:PORT,
async fetch(request){
// const body = figlet.textSync("Hey There !");
const {method} = request;
const {pathname} = new URL(request.url);
const pathRegexForID = /^\/api\/posts\/(\d+)$/;
if (method == "GET" && pathname == "/api/posts"){
const match = pathname.match(pathRegexForID);
const id = match && match[1];
if (id){
return handleGetPostById(id);
}
}
if (method == "GET" && pathname == "/api/posts"){
return handleGetAllPosts();
}
if (method == "POST" && pathname == "/api/posts"){
const newPost = await request.json();
return handleCreatePost(newPost.title, newPost.content);
}
if (method == "PATCH" && pathname == "/api/posts"){
const editedPost = await request.json();
return handleUpdatePost(editedPost.id, editedPost.title, editedPost.content);
}
if (method == "DELETE" && pathname == "/api/posts"){
const {id} = await request.json();
return handleDeletePost(id);
}
return new Response('Not Found', {status: 404});
}
});
console.log("Server is running on port", PORT);