-
Notifications
You must be signed in to change notification settings - Fork 0
/
controllers.js
108 lines (87 loc) · 3.03 KB
/
controllers.js
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
import articles from "./db.json" assert { type: "json" };
import { writeJsonSync } from "https://deno.land/std/fs/mod.ts";
const articlesList = (context) => {
context.response.body = articles
}
const articleDetail = (context) => {
const article = articles.find(a => a.id == context.params.id)
if (article) {
context.response.body = article
} else {
context.response.status = 404
context.response.body = `Article with id: ${context.params.id} not found.`
}
}
const articleAdd = async (context) => {
const body = await context.request.body()
if (body.type == "json") {
const value = body.value
value.id = articles.slice(-1)[0].id + 1
if (value.title && value.content) {
articles.push(value)
writeJsonSync("./db.json", articles, { spaces: 4 })
context.response.status = 201
context.response.body = value
} else {
context.response.status = 400
context.response.body = `"title" and "content" can't be empty.`
}
} else {
context.response.status = 400
context.response.body = `Data should be in Json.`
}
}
const articleUpdate = async (context) => {
const article = articles.find(a => a.id == context.params.id)
if (article) {
const body = await context.request.body()
if (body.type == "json") {
const value = body.value
value.id = article.id
if (value.title && value.content) {
for (var i = articles.length - 1; i >= 0; i--) {
if (articles[i].id == article.id) {
articles[i] = value
break
}
}
writeJsonSync("./db.json", articles, { spaces: 4 })
context.response.status = 200
context.response.body = value
} else {
context.response.status = 400
context.response.body = `"title" and "content" can't be empty.`
}
} else {
context.response.status = 400
context.response.body = `Data should be in Json.`
}
} else {
context.response.status = 404
context.response.body = `Article with id: ${context.params.id} not found.`
}
}
const articleDelete = (context) => {
const article = articles.find(a => a.id == context.params.id)
if (article) {
for (var i = articles.length - 1; i >= 0; i--) {
if (articles[i].id == article.id) {
articles.splice(i, 1)
break
}
}
writeJsonSync("./db.json", articles, { spaces: 4 })
context.response.status = 200
context.response.body = `Article with id: ${context.params.id} removed.`
} else {
context.response.status = 404
context.response.body = `Article with id: ${context.params.id} not found.`
}
};
export {
articlesList,
articleDetail,
articleAdd,
articleUpdate,
articleDelete
};