-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
34 lines (30 loc) · 673 Bytes
/
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
import mongoose from 'mongoose'
const {Types: {ObjectId}} = mongoose
/**
* Extend Joi with ObjectId validation
*/
export default Joi => ({
type: 'objectId',
base: Joi.any(),
messages: {
objectId: 'needs to be a valid ObjectId',
},
coerce(value) {
//No value
if (!value) {
return
}
//Convert string to object ID
if (typeof value === 'string' && value.match(/^[0-9a-fA-F]{24}$/)) {
value = new ObjectId(value)
}
//Return new value
return {value}
},
validate(value, helpers) {
if (!(value instanceof ObjectId)) {
const errors = helpers.error('objectId')
return {value, errors};
}
},
})