-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathroutes.ts
109 lines (94 loc) · 2.63 KB
/
routes.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
import { Router, RouterContext } from 'https://deno.land/x/oak/mod.ts'
import { Response } from "https://deno.land/x/oak/response.ts";
interface Todo {
description: string
id: number
}
let todos: Array<Todo> = [
{
description: 'Todo 1',
id: 1,
},
{
description: 'Todo 2',
id: 2,
},
]
export const getTodos = (c: RouterContext) => {
c.response.body = todos
}
export const getTodo = ({
params,
response,
}: {
params: {
id: string
}
response: any
}) => {
const todo = todos.filter((todo) => todo.id === parseInt(params.id))
if (todo.length) {
response.status = 200
response.body = todo[0]
return
}
response.status = 400
response.body = { msg: `Cannot find todo ${params.id}` }
}
export const addTodo = async (c: RouterContext) => {
const body = await c.request.body()
const { description, id }: { description: string; id: number } = body.value
todos.push({
description: description,
id: id,
})
c.response.body = { msg: 'OK' }
c.response.status = 200
}
export const updateTodo = async (c: RouterContext) => {
const id = c.params.id
let response = c.response
if(id){
const temp = todos.filter((existingTodo) => existingTodo.id === parseInt(id))
const body = await c.request.body()
const description: string = body.value.description
if (temp.length) {
temp[0].description = description
response.status = 200
response.body = { msg: 'OK' }
return
}
}
response.status = 400
response.body = { msg: `Cannot find todo ${c.params.id}` }
}
type RemoveContext = {
params: {
id: string
}
response: Response
}
export const removeTodo = (c: RemoveContext) => {
const lengthBefore = todos.length
todos = todos.filter((todo) => todo.id !== parseInt(c.params.id))
let response = c.response
if (todos.length === lengthBefore) {
response.status = 400
response.body = { msg: `Cannot find todo ${c.params.id}` }
return
}
response.body = { msg: 'OK' }
response.status = 200
}
export const getHome = (c: RouterContext) => {
c.response.body = 'Deno API server is running...'
c.response.status = 200
}
export const router = new Router()
router
.get('/', getHome)
.get('/todos', getTodos)
.get('/todos/:id', getTodo)
.post('/todos', addTodo)
.put('/todos/:id', updateTodo)
.delete('/todos/:id', removeTodo)