-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
253 lines (183 loc) · 7.39 KB
/
index.js
File metadata and controls
253 lines (183 loc) · 7.39 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
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
const express = require('express')
const request = require('request')
require('dotenv').config()
const { sequelize, User, Article, Comment } = require('./models')
const { hasValidApiKeyHeader, generateAccessToken, hasValidJwt } = require('./utils/auth')
const app = express()
const PORT = process.env.PORT || 3001
app.use(express.json())
app.post('/login', hasValidApiKeyHeader, async (req, res) => {
const { username, password } = req.body
const user = req.user
try {
if (user.username === username && user.password === password) {
const wholeToken = generateAccessToken({ username: username })
return res.status(201).json(wholeToken)
} else {
return res.status(400).json({
code: "INVALID_CREDENTIALS",
message: "Password is invalid"
})
}
} catch (error) {
return res.status(500).json(err)
}
})
app.post('/tenants', async (req, res) => {
const { username, password } = req.body
// write to db new user
try {
const user = await User.create({ username, password })
return res.status(201).json(user)
} catch (err) {
console.log(err)
return res.status(500).json(err)
}
})
app.get('/tenants/:tenantId', async (req, res) => {
const { tenantId } = req.params
// get user from db with concrete ID
try {
const user = await User.findOne({ where: { tenantId } })
return res.json(user)
} catch (err) {
console.log(err)
return res.status(500).json({ error: 'Something went wrong' })
}
})
app.get('/articles', hasValidApiKeyHeader, async (req, res) => {
try {
const { offset = 0, limit = 0 } = req.query
let articles
// PAGINATION
// If exist limit from user, use them
if (limit > 0) {
articles = await Article.findAndCountAll({
limit: limit,
offset: offset,
})
// Else return all articles without pagination
} else {
articles = await Article.findAndCountAll()
}
return res.json(articles)
} catch (err) {
console.log(err)
return res.status(500).json({ error: 'Something went wrong' })
}
})
app.post('/articles', hasValidJwt, hasValidApiKeyHeader, async (req, res) => {
const { title, perex } = req.body
// create article to db with params from body
try {
const article = await Article.create({ title, perex })
return res.json(article)
} catch (err) {
console.log(err)
return res.status(400).json(err)
}
})
app.get('/articles/:articleId', hasValidApiKeyHeader, async (req, res) => {
const { articleId } = req.params
// get concrete article
try {
const article = await Article.findOne({ where: { articleId } })
return res.json(article)
} catch (err) {
console.log(err)
return res.status(500).json({ error: 'Something went wrong' })
}
})
app.delete('/articles/:articleId', hasValidApiKeyHeader, hasValidJwt, async (req, res) => {
const { articleId } = req.params
// Find concrete article and destry him
try {
const article = await Article.findOne({ where: { articleId } })
await article.destroy()
return res.status(204).json({ message: 'Article deleted!' })
} catch (err) {
console.log(err)
return res.status(500).json({ error: 'Something went wrong' })
}
})
app.patch('/articles/:articleId', hasValidJwt, hasValidApiKeyHeader, async (req, res) => {
const { articleId } = req.params
const { title, perex } = req.body
// Find concrete article, take non empty value and update them
try {
const article = await Article.findOne({ where: { articleId } })
if (perex) {
article.perex = perex
}
if (title) {
article.title = title
}
await article.save()
return res.json(article)
} catch (err) {
console.log(err)
return res.status(500).json({ error: 'Something went wrong' })
}
})
app.post('/comments', hasValidApiKeyHeader, async (req, res) => {
const { tenantId, content, articleId } = req.body
// 3 query to db - it is helpfull query. As first I have tenant id, then I have article id and last create new comment with this data
try {
const user = await User.findOne({ where: { tenantId } })
const article = await Article.findOne({ where: { articleId } })
const comment = await Comment.create({ content, userId: user.id, articleId: article.id })
// response is with author and article ID
const articleWithAuthor = Object.assign(comment.toJSON(), { author: user.toJSON().username }, { articleId: article.toJSON().articleId })
return res.status(201).json(articleWithAuthor)
} catch (err) {
console.log(err)
return res.status(500).json({ error: 'Something went wrong' })
}
})
app.post('/comments/:commentId/vote/up', hasValidApiKeyHeader, async (req, res) => {
const { commentId } = req.params
// Increase score by 1
try {
await Comment.increment('score', { where: { commentId } });
const comment = await Comment.findOne({ where: { commentId } })
const user = await User.findOne({ where: { id: comment.userId } })
// add more rows with information to final JSON, from other tables
const articleWithAuthor = Object.assign(comment.toJSON(), { author: user.toJSON().username })
return res.status(201).json(articleWithAuthor)
} catch (err) {
return res.status(500).json({ error: 'Something went wrong' })
}
})
app.post('/comments/:commentId/vote/down', hasValidApiKeyHeader, async (req, res) => {
const { commentId } = req.params
// Decrease score by 1
try {
await Comment.decrement('score', { where: { commentId } });
const comment = await Comment.findOne({ where: { commentId } })
const user = await User.findOne({ where: { id: comment.userId } })
// add more rows with information to final JSON, from other tables
const articleWithAuthor = Object.assign(comment.toJSON(), { author: user.toJSON().username })
return res.status(201).json(articleWithAuthor)
} catch (err) {
}
})
// Routes for images are not complete. I add only notes how to do it. All routes will work with binary files
app.get('/images/:imageId', async (req, res) => {
// Here will be a new table and imageID from params
// As first will read from table Image name of concrete image file (now doesn't exists table)
// then send a file from route below (__dirname + '/images/' + nameOfFileFromTable)
// res.sendFile(__dirname + '/images/image1.png')
})
app.post('/images/:imageId', async (req, res) => {
// Here will write to table images a new row. This row will have a imageId and imageName - both in uuid
// as next the file will save via fs library with new name (generated uuid) - because older files could be overwites
// Last step will be load file and send via res.sendFile
})
app.delete('/images/:imageId', async (req, res) => {
// Similar as post route, only as first should delete a file and then will delete from table
})
app.listen(PORT, async () => {
console.log(`Server is running on port ${PORT}`)
await sequelize.authenticate()
console.log('Database synced!')
})