-
Notifications
You must be signed in to change notification settings - Fork 0
/
chats.js
140 lines (131 loc) · 3.39 KB
/
chats.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
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
140
const Router = require('koa-router');
const queries = require('../db/queries/chats');
const user_chat_queries = require('../db/queries/user_chat');
const router = new Router();
const BASE_URL = `/api/v1/chats`;
router.get(BASE_URL, async (ctx) => {
try {
const chats = await queries.getAllChats();
ctx.body = {
status: 'success',
data: chats
};
}
catch (err) {
console.log(err) ;
}
});
router.get(`${BASE_URL}/:id`, async (ctx) => {
try {
const chat = await queries.getSingleChat(ctx.params.id);
if (chat.length) {
ctx.body = {
status: 'success',
data: chat
};
}
else {
ctx.status = 404;
ctx.body = {
status: 'error',
message: 'That chat does not exist.'
};
}
}
catch (err) {
console.log(err);
}
});
router.post(BASE_URL, async (ctx) => {
try {
const { created_at , user_ids } = ctx.request.body;
const chat_list = await queries.addChat({ created_at });
const chat = chat_list[0];
if (chat) {
ctx.status = 201;
ctx.body = {
status: 'success',
data: chat
};
try {
await Promise.all(user_ids.map((user_id) => {
return user_chat_queries.addUserChat(user_id, chat.id)
}));
}
catch (err) {
ctx.status = 400;
ctx.body = {
status: 'error',
message: err.chat || 'Sorry, an error has occured.'
};
}
}
else {
ctx.status = 400;
ctx.body = {
status: 'error',
message: 'Something went wrong.'
};
}
}
catch (err) {
ctx.status = 400;
ctx.body = {
status: 'error',
message: err.chat || 'Sorry, an error has occured.'
};
}
})
router.put(`${BASE_URL}/:id`, async (ctx) => {
try {
const chat = await queries.updateChat(ctx.params.id, ctx.request.body);
if (chat.length) {
ctx.status = 200;
ctx.body = {
status: 'success',
data: chat
}
}
else {
ctx.status = 404;
ctx.body = {
status: 'error',
message: 'That chat does not exist.'
}
}
}
catch (err) {
ctx.status = 400;
ctx.body = {
status: 'error',
message: err.message || 'Sorry, an error has occured.'
};
}
})
router.delete(`${BASE_URL}/:id`, async (ctx) => {
try {
const chat = await queries.deleteChat(ctx.params.id);
if (chat.length) {
ctx.status = 200;
ctx.body = {
status: 'success',
data: chat
}
}
else {
ctx.status = 404;
ctx.body = {
status: 'error',
message: 'That chat does not exist.'
}
}
}
catch (err) {
ctx.status = 400;
ctx.body = {
status: 'error',
message: err.message || 'Sorry, an error has occured.'
};
}
})
module.exports = router;