-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
61 lines (49 loc) · 1.3 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
class AppBootHook {
constructor(app) {
this.app = app
app.config.coreMiddleware.unshift('history', 'docs', 'compress')
}
async didLoad() {
const { mongoose, config } = this.app
const { url } = this.app.config.mongoose
mongoose.connection.once('close', async () => {
console.log(`Database is closed on ${url}`)
})
mongoose.connection.on('error', error => console.error(error))
}
serverDidReady() {
const { validator, mongoose } = this.app
validator.addRule('objectId', (rule, value) => {
try {
mongoose.Types.ObjectId(value)
} catch (err) {
return err.message
}
})
validator.addRule('objectIdList', (rule, value) => {
try {
var validationResult = validator.validate(
{
objectIdList: {
type: 'array',
itemType: 'objectId',
min: rule.min || 1,
},
},
{ objectIdList: value }
)
} catch (error) {
return error.message
}
if (validationResult) {
return validationResult.map((item, index) => {
item.field = `[${index}]`
return item
})
}
})
console.log('Server did ready')
global.app = this.app
}
}
module.exports = AppBootHook