-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
116 lines (107 loc) · 2.72 KB
/
index.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
const logger = require('./logger')
/**
* @function checkRequest
* This method is used in express middleware. It will check the incoming request with required request.
* @param {Object} requiredRequest
* @returns {function(...[*]=)}
*/
function checkRequest (requiredRequest) {
return async (req, res, next) => {
let valid = true
for (const type in requiredRequest) {
if (type === 'file') {
if (!(req.file.fieldname === requiredRequest[type])) {
if (process.env.NODE_ENV !== 'production') {
logger.info('Missing \'file\' field')
}
valid = false
}
} else {
requiredRequest[type].forEach(parameterName => {
if (!(parameterName in req[type])) {
if (process.env.NODE_ENV !== 'production') {
logger.info(`Missing ${parameterName} field`)
}
valid = false
}
})
}
}
if (!valid) {
res
.status(requestResponse.incomplete_body.code)
.json(requestResponse.incomplete_body)
} else {
next()
}
}
}
/**
* @function checkRequiredProperties
* This method is an alternative method from checkRequest, but can be used more universal, not limited only to express middleware.
* @param {Object} requiredProperties
* @param {Object} properties
* @returns {boolean}
*/
function checkRequiredProperties (requiredProperties, properties) {
let valid = true
for (const type in requiredProperties) {
requiredProperties[type].forEach(parameterName => {
if (!(parameterName in properties[type])) {
if (process.env.NODE_ENV !== 'production') {
logger.info(`Missing ${parameterName} field`)
}
valid = false
}
})
}
return valid
}
const requestResponse = {
success: {
code: 200,
status: true,
message: 'Success.'
},
incomplete_body: {
code: 400,
status: false,
message: 'Bad request. Please check your request data.'
},
unauthorized: {
code: 401,
status: false,
message:
'E-mail or password does not match, or you are not authorized to accessing this page.'
},
not_found: {
code: 404,
status: false,
message: 'Resource not found.'
},
unprocessable_entity: {
code: 422,
status: false,
message: 'The request you sent is unable to process.'
},
server_error: {
code: 500,
status: true,
message: 'Internal server error. Please contact the administrator.'
}
}
const mongoOptions = {
keepAlive: true,
poolSize: 10,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
autoIndex: false
}
module.exports = {
logger,
checkRequest,
checkRequiredProperties,
mongoOptions,
requestResponse
}