-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
358 lines (293 loc) · 10.2 KB
/
app.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
const express = require('express');
const app = express();
const knex = require('knex')(require('./knexfile.js')[process.env.NODE_ENV || 'development']);
const cors = require('cors');
const PORT = 3001
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(cors())
//get user_id by user_name
async function getUserIdByUserName(userName) {
return await knex.select('id')
.from('users')
.where('user_name', userName)
.then(data => {
if (data.length === 0) {
return null
}
return data[0].id
})
}
//get template_id by user_id //produces a list of template_id's of all docs associated with user_id
async function getTemplateIdHistoryByUserId(userId) {
return await knex.select('template_id')
.from('users_templates')
.where('user_id', userId)
.then(async (data) => {
let valueArr = [];
for (let n = 0; n < data.length; n++) {
valueArr.push(data[n].template_id)
}
return valueArr
})
}
//get template by template_id
async function getTemplateByTemplateId(templateId) {
return await knex.select('*')
.from('templates')
.where('id', templateId)
.then(template => template[0])
}
//get template options by template_id
async function getTemplateOptionsByTemplateId(templateId) {
return await knex.select('*')
.from('template_options')
.where('template_id', templateId)
// .then(arr => arr.map((obj => { return { ...obj, option_value: JSON.parse(obj.option_value) } })))
}
//get serialized options by user_id and template_id
async function getSerializedOptionsByUserIdAndTemplateId(userId, templateId) {
return await knex.select('*')
.from('users_templates')
.where('template_id', templateId)
.andWhere('user_id', userId)
// .then(arr => arr.map((obj => { return { history_id: obj.history_id, serialized_options: JSON.parse(obj.serialized_options) } })))
}
//get all serialized options
async function getSerializedOptions() {
return await knex.select('*')
.from('users_templates')
}
//get serialized options by user_id
async function getSerializedOptionsByUserId(userId) {
return await knex.select('*')
.from('users_templates')
.where('user_id', userId)
}
//get serialized options by history_id
async function getSerializedOptionsByHistoryId(historyId) {
return await knex.select('*')
.from('users_templates')
.where('history_id', historyId)
}
//returns {template: [], template_options: [], serialized_options: [{}]}
async function getHistoryRecord(userId, templateId) {
let history = {}
history.template = await getTemplateByTemplateId(templateId)
history.template_options = await getTemplateOptionsByTemplateId(templateId)
history.history_object = await getSerializedOptionsByUserIdAndTemplateId(userId, templateId)
return history
}
async function getHistoryByUserId(userId) {
let historyArr = [];
let serializedOptionsArray = await getSerializedOptionsByUserId(userId) //array of all userId's serializedOptions from users_templates
for (let history_object of serializedOptionsArray) {
let template = await getTemplateByTemplateId(history_object.template_id)
let template_options = await getTemplateOptionsByTemplateId(history_object.template_id)
historyArr.push({ history_object, template, template_options })
}
return historyArr
}
//admin feature
app.get('/users', async (req, res) => {
let userList = await knex('users').select('*')
res.json(userList)
})
//create new user
app.post('/users', async (req, res) => {
let { user_name, password } = req.body
await knex('users').where({ user_name }).then(result => {
if (result.length > 0) {
res.status(409).send('Username already exists')
} else {
knex('users')
.insert({ user_name, password })
.returning(['id', 'user_name'])
.then(newUser => res.status(201).json(newUser[0]))
}
})
})
//login/load user
app.get('/users/:user_name', (req, res) => {
let user = req.params.user_name
knex.select('id', 'user_name')
.from('users')
.where('user_name', user)
.then(data => {
if (data.length > 0) {
res.status(200).json(data[0])
}
else {
res.status(404).json('User not found, please input a different username')
}
})
.catch(err =>
res.status(404).json({
message:
'The data you are looking for could not be found. Please try again'
})
);
})
//get history of created documents
app.get('/users/:user_name/history', async (req, res) => {
let user = req.params.user_name
let userId = await getUserIdByUserName(user);
let history = await getHistoryByUserId(userId)
res.json(history)
})
app.post('/login', (req, res) => {
let user_name = req.body.user_name
let password = req.body.password
knex.select('id', 'user_name')
.from('users')
.where({ user_name })
.andWhere({ password })
.then((result) => {
if (result.length < 1) {
res.status(401).send("Invalid login")
} else {
res.json(result[0])
}
})
})
//get all history
app.get('/history', async (req, res) => {
let options = await getSerializedOptions() //array of all serializedOptions from users_templates
res.json(options)
})
//get document by history_id
app.get('/history/:history_id', async (req, res) => {
let history_id = req.params.history_id
let options = await getSerializedOptionsByHistoryId(history_id) //array of all serializedOptions from users_templates
if (options.length === 0) {
res.status(404).send('History ID not found')
return
}
let history_object = options[0]
let template = await getTemplateByTemplateId(history_object.template_id)
let template_options = await getTemplateOptionsByTemplateId(history_object.template_id)
let historyObject = { history_object, template, template_options }
res.json(historyObject)
})
//post history
app.post('/users/:user_name/history', async (req, res) => {
let user = req.params.user_name
let template_id = req.body.template_id
let file_name = req.body.file_name
let serialized_options = JSON.stringify(req.body.serialized_options)
let user_id = await getUserIdByUserName(user)
await knex('users_templates')
.insert({ user_id, template_id, file_name, serialized_options })
.returning('*')
.then(history => {
res.status(201).json(history[0])
});
})
//replacing old serialized options with newly fed serialized_options
app.patch('/history', async (req, res) => {
let serialized_options = JSON.stringify(req.body.serialized_options)
let history_id = req.body.history_id
let file_name = req.body.file_name
let newHistory = await knex('users_templates')
.where('history_id', history_id)
.update({ serialized_options, file_name })
.returning('*')
res.status(200).json(newHistory[0])
})
//delete a doc from history
app.delete('/users/:user_name/history/:history_id', async (req, res) => {
let user = req.params.user_name
let idToDelete = parseInt(req.params.history_id)
await knex('users_templates')
.where('history_id', idToDelete)
.del()
let user_id = await getUserIdByUserName(user)
let history = await getHistoryByUserId(user_id)
res.json(history)
})
//get users favorites GET /users/:user_name/favorites
app.get('/users/:user_name/favorites', async (req, res) => {
let user = req.params.user_name;
let userId = await getUserIdByUserName(user)
if (!userId) {
res.status(404).send('User not found')
return
}
let favorites = await knex.select('template_id')
.from('favorites')
.where('user_id', userId)
.then(async (data) => {
let favoriteTemplateId = await data.map((element) => element.template_id)
return favoriteTemplateId
})
res.send(favorites)
})
//add to favorites
app.post('/users/:user_name/favorites/:template_id', async (req, res) => {
let user = req.params.user_name;
let userId = await getUserIdByUserName(user)
let templateId = parseInt(req.params.template_id, 10)
let favorites = await knex.select('template_id')
.from('favorites')
.where('user_id', userId)
.then(async (data) => {
let favoriteTemplateId = await data.map((element) => element.template_id)
return favoriteTemplateId
})
if (favorites.includes(templateId) === false) {
await knex('favorites').insert({ user_id: userId, template_id: templateId }).returning('template_id')
}
favorites = await knex.select('template_id')
.from('favorites')
.where('user_id', userId)
.then(async (data) => {
let favoriteTemplateId = await data.map((element) => element.template_id)
return favoriteTemplateId
})
res.status(201).json(favorites)
})
//delete a favorite
app.delete('/users/:user_name/favorites/:template_id', async (req, res) => {
let userId = await getUserIdByUserName(req.params.user_name)
await knex('favorites')
.select('template_id')
.where('user_id', userId)
.andWhere('template_id', req.params.template_id)
.del()
let newFavorites = await knex.select('template_id')
.from('favorites')
.where('user_id', userId)
.then(async (data) => {
let favoriteTemplateId = await data.map((element) => element.template_id)
return favoriteTemplateId
})
res.json(newFavorites)
})
//get a list of all templates (id, title, body, options)
app.get('/templates', async (req, res) => {
let templateTable = await knex.select('id', 'title', 'body')
.from('templates')
let templateOutput = [];
for (let i of templateTable) {
let template = await knex.select('id', 'title', 'body')
.from('templates')
.where('id', i.id)
template_options = await getTemplateOptionsByTemplateId(i.id)
templateOutput.push({ template: template[0], template_options })
}
res.status(200).json(templateOutput)
})
//get template body and options by id
app.get('/templates/:template_id', async (req, res) => {
let templateId = req.params.template_id
let template = await knex.select('id', 'title', 'body')
.from('templates')
.where('id', templateId)
template_options = await getTemplateOptionsByTemplateId(templateId)
let templateOutput = { template: template[0], template_options }
res.status(200).send(templateOutput)
})
app.listen(PORT, () => {
console.log(`Mjolnir is bringing the hammer down on ${PORT}`);
});
module.exports = app;