-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.js
343 lines (292 loc) · 9.15 KB
/
main.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
require('dotenv').config()
const jsonServer = require('json-server')
const queryString = require('query-string')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults({
static: './public',
})
const yup = require('yup')
const jwt = require('jsonwebtoken')
const uniqid = require('uniqid')
const multer = require('multer')
const fs = require('fs')
const casual = require('casual')
const PATHS = {
POSTS_FOLDER: './public/posts',
WORKS_FOLDER: './public/works',
}
// Setup upload config
function getStorage(storedPath) {
return multer.diskStorage({
destination: function (req, file, cb) {
const path = storedPath
fs.mkdirSync(path, { recursive: true })
cb(null, path)
},
filename: function (req, file, cb) {
const [fileName, fileExtension] = file.originalname.split('.')
cb(null, uniqid(`${fileName}-`, `.${fileExtension}`))
},
})
}
function upload(toPath) {
return multer({
storage: getStorage(toPath),
limits: {
fileSize: 5000000, // 5mb = 5000000 bytes
},
fileFilter: (req, file, cb) => {
if (
file.mimetype === 'image/png' ||
file.mimetype === 'image/jpg' ||
file.mimetype === 'image/jpeg'
) {
cb(null, true)
} else {
cb(null, false)
return cb(new Error('Only .png, .jpg and .jpeg format allowed!'))
}
},
})
}
function uploadSingle(toPath, fieldName) {
return (req, res, next) => {
const action = upload(toPath).single(fieldName)
action(req, res, (error) => {
if (error) {
// A Multer error occurred when uploading.
return res.status(400).jsonp({
error: error.message || 'Failed to upload file with unknown reason.',
})
}
// Everything went fine.
next()
})
}
}
const port = process.env.PORT || 3000
const PRIVATE_KEY = 'ae9468ec-c1fe-4cce-9772-cd899a2b496a'
const SECONDS_PER_DAY = 60 * 60 * 24
// Set default middlewares (logger, static, cors and no-cache)
server.use(middlewares)
// To handle POST, PUT and PATCH you need to use a body-parser
// You can use the one used by JSON Server
server.use(jsonServer.bodyParser)
server.use((req, res, next) => {
const now = Date.now()
switch (req.method) {
case 'POST': {
req.body.createdAt = now
req.body.updatedAt = now
}
case 'PATCH': {
req.body.updatedAt = now
}
}
// Continue to JSON Server router
next()
})
function handleAddPost(req, res, next) {
const now = Date.now()
if (req.file?.filename) {
req.body.imageUrl = `${process.env.STATIC_URL}/posts/${req.file?.filename}`
}
req.body.createdAt = now
req.body.updatedAt = now
next()
}
function handleUpdatePost(req, res, next) {
const now = Date.now()
if (req.file?.filename) {
req.body.imageUrl = `${process.env.STATIC_URL}/posts/${req.file?.filename}`
}
req.body.updatedAt = now
next()
}
function validateFormData(req, res, next) {
const contentType = req.headers['content-type']
if (!contentType.includes('multipart/form-data')) {
return res
.status(400)
.json({ error: 'Invalid Content-Type, only multipart/form-data is supported.' })
}
next()
}
function handleUploadFile(req, res, next) {
if (!['PATCH', 'POST'].includes(req.method)) {
return res.status(404).json({ error: 'Not Found' })
}
if (req.method === 'PATCH') return handleUpdatePost(req, res, next)
return handleAddPost(req, res, next)
}
server.use(
'/api/with-thumbnail',
validateFormData,
uploadSingle(PATHS.POSTS_FOLDER, 'image'),
handleUploadFile,
router
)
server.post('/api/login', async (req, res) => {
const loginSchema = yup.object().shape({
username: yup
.string()
.required('Missing username')
.min(4, 'username should have at least 4 characters'),
password: yup
.string()
.required('Missing password')
.min(6, 'password should have at least 6 characters'),
})
try {
await loginSchema.validate(req.body)
} catch (error) {
return res.status(400).jsonp({ error: error.errors?.[0] || 'Invalid username or password' })
}
// validate username and password
const { username, password } = req.body
const token = jwt.sign({ sub: username }, PRIVATE_KEY, { expiresIn: SECONDS_PER_DAY })
const expiredAt = new Date(Date.now() + SECONDS_PER_DAY * 1000).getTime()
// if valid, generate a JWT and return, set it expired in 1 day
return res.status(200).jsonp({ accessToken: token, expiredAt })
})
function protectedRoute(req, res, next) {
try {
const authHeader = req.headers.authorization
if (!authHeader) return res.status(401).json({ message: 'You need to login to access' })
const [tokenType, accessToken] = authHeader.split(' ')
if (tokenType !== 'Bearer') {
return res.status(401).json({ message: 'Invalid token type. Only "Bearer" supported' })
}
jwt.verify(accessToken, PRIVATE_KEY)
next()
} catch (error) {
return res.status(401).json({ message: 'Access token is not valid or expired.' })
}
}
server.get('/api/profile', protectedRoute, (req, res) => {
try {
const authHeader = req.headers.authorization
const [tokenType, accessToken] = authHeader.split(' ')
const payload = jwt.decode(accessToken)
return res.status(200).json({
username: payload.sub,
city: casual.city,
email: casual.email.toLowerCase(),
})
} catch (error) {
console.log('failed to parse token', error)
return res.status(400).json({ message: 'Failed to parse token.' })
}
})
// private apis
server.use('/api/private', protectedRoute, router)
// Works APIs
async function validateAddWorkPayload(req, res, next) {
const workSchema = yup.object().shape({
title: yup.string().required('Missing title'),
shortDescription: yup
.string()
.required('Missing shortDescription')
.max(1000, 'shortDescription is too long (max length 1000)'),
fullDescription: yup.string().required('Missing fullDescription'),
thumbnailUrl: yup.string().required('Missing thumbnail image file'),
tagList: yup.array().required('Missing tagList').max(5, 'Too many tags (max is 5)'),
})
try {
console.log('validate add', req.body)
await workSchema.validate(req.body)
next()
} catch (error) {
return res.status(400).jsonp({
error: error.errors?.[0] || 'Invalid payload, please help to double check and try again.',
})
}
}
async function validateUpdateWorkPayload(req, res, next) {
const workSchema = yup.object().shape({
title: yup.string().optional(),
shortDescription: yup
.string()
.optional()
.max(1000, 'shortDescription is too long (max length 1000)'),
fullDescription: yup.string().optional(),
thumbnailUrl: yup.string().optional(),
tagList: yup.array().optional().max(5, 'Too many tags (max is 5)'),
})
try {
console.log('validate update', req.body)
await workSchema.validate(req.body)
next()
} catch (error) {
return res.status(400).jsonp({
error: error.errors?.[0] || 'Invalid payload, please help to double check and try again.',
})
}
}
function addThumbnailUrl(req, res, next) {
if (req.file?.filename) {
req.body.thumbnailUrl = `${process.env.STATIC_URL}/works/${req.file?.filename}`
}
const now = Date.now()
if (req.method === 'POST') req.body.createdAt = now
req.body.updatedAt = now
next()
}
function transformTagList(req, res, next) {
// req.body.tagList is a string
// convert 1,2,3 => ["1", "2", "3"]
const tagList = req.body.tagList
// in case tagList is null/undefined --> do nothing (FE want to ignore it)
// in case tagList is an empty string --> they want to reset it
if (tagList == null || typeof tagList !== 'string') return next()
req.body.tagList = tagList.split(',').filter((x) => Boolean(x))
next()
}
server.post(
'/api/works',
protectedRoute,
validateFormData,
uploadSingle(PATHS.WORKS_FOLDER, 'thumbnail'),
addThumbnailUrl,
transformTagList,
validateAddWorkPayload
)
server.patch(
'/api/works/:id',
protectedRoute,
validateFormData,
uploadSingle(PATHS.WORKS_FOLDER, 'thumbnail'),
addThumbnailUrl,
transformTagList,
validateUpdateWorkPayload
)
server.delete('api/works/:id', protectedRoute)
// Customize response
router.render = (req, res) => {
const headers = res.getHeaders()
// In case of header x-total-count is available
// It means client request a list of resourses with pagination
// Then we should include pagination in response
// Right now, json-server just simply return a list of data without pagination data
const totalCountHeader = headers['x-total-count']
if (req.method === 'GET' && totalCountHeader) {
// Retrieve request pagination
const queryParams = queryString.parse(req._parsedUrl.query)
const result = {
data: res.locals.data,
pagination: {
_page: Number.parseInt(queryParams._page) || 1,
_limit: Number.parseInt(queryParams._limit) || 10,
_totalRows: Number.parseInt(totalCountHeader),
},
}
return res.jsonp(result)
}
res.jsonp(res.locals.data)
}
// Use default router
server.use('/api', router)
server.listen(port, () => {
console.log('JSON Server is running at port', port)
})