Repository navigation
Expand file tree
/
Copy pathhandler.js
More file actions
139 lines (101 loc) · 2.65 KB
/
Copy pathhandler.js
File metadata and controls
139 lines (101 loc) · 2.65 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
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
const { nanoid } = require('nanoid');
const notes = require('./notes');
const addNoteHandler = (request, h) => {
const { title, tags, body } = request.payload;
const id = nanoid(16);
const createdAt = new Date().toISOString();
const updatedAt = createdAt;
const newNote = {
title, tags, body, id, createdAt, updatedAt
};
notes.push(newNote);
const isSuccess = notes.filter((note) => note.id == id).length > 0;
if (isSuccess) {
const response = h.response({
status: 'success',
message: 'Added note successfully!',
data: {
noteId: id
}
});
response.code(201);
return response;
}
const response = h.response({
status: 'fail',
message: 'Failed to add note!',
});
response.code(500);
return response;
};
const getAllNotesHandler = () => ({
status: 'success',
data: {
notes,
},
});
const getNoteByIdHandler = (request, h) => {
const { id } = request.params;
const note = notes.filter((n) => n.id === id)[0];
if (note != undefined) {
return {
status: 'success',
data: {
note
},
};
}
const response = h.response({
status: 'fail',
message: 'Cannot found any note!',
});
response.code(404);
return response;
};
const editNoteByIdHandler = (request, h) => {
const { id } = request.params;
const { title, tags, body } = request.payload;
const updateAt = new Date().toISOString();
const index = notes.findIndex((note) => note.id === id);
if (index !== -1) {
notes[index] = {
...notes[index],
title,
tags,
body,
updateAt,
};
const response = h.response({
status: 'success',
message: 'Update note successfully!',
});
response.code(200);
return response;
}
const response = h.response({
status: 'fail',
message: 'Cannot update note!'
});
response.code(404);
return response;
};
const deleteNoteByIdHandler = (request, h) => {
const { id } = request.params;
const index = notes.findIndex((note) => note.id === id);
if (index !== -1) {
notes.splice(index, 1);
const response = h.response({
status: 'success',
message: 'Delete note successfully!',
});
response.code(200);
return response;
}
const response = h.response({
status: 'fail',
message: 'Cannot found any note!'
});
response.code(404);
return response;
}
module.exports = { addNoteHandler, getAllNotesHandler, getNoteByIdHandler, editNoteByIdHandler, deleteNoteByIdHandler };