Created
February 2, 2017 13:35
-
-
Save aegyed91/3665f8e0eb3d1ced4c2efb59382465b2 to your computer and use it in GitHub Desktop.
joi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Joi = require('joi'); | |
module.exports = Joi.extend([ | |
{ | |
base: Joi.string(), | |
name: 'string', | |
language: { | |
objectid: 'needs to be a valid object id', | |
sha: 'needs to be a valid sha string' | |
}, | |
rules: [ | |
{ | |
name: 'objectid', | |
description: 'Determine if the id is a valid mongo object id.', | |
validate(params, value, state, options) { | |
if (!_.isObjectId(value)) { | |
return this.createError('string.objectid', { v: value }, state, options); | |
} | |
return value; | |
} | |
}, | |
{ | |
name: 'sha', | |
description: 'Determine if the id is a valid sha string.', | |
validate(params, value, state, options) { | |
if (!_.isSha(value)) { | |
return this.createError('string.sha', { v: value }, state, options); | |
} | |
return value; | |
} | |
} | |
] | |
}, | |
{ | |
base: Joi.any(), | |
name: 'any', | |
language: { | |
image: 'needs to be an image with .gif .png, .jpg, .jpeg extension.', | |
isJS: 'needs to be javascript file with a .js extension.', | |
isJSON: 'needs to be json file with a .json extension.' | |
}, | |
rules: [ | |
{ | |
name: 'image', | |
validate(params, value, state, options) { | |
const mimeType = value.hapi.headers['content-type']; | |
const regex = /(jpeg|png|gif|jpg)/i; | |
if (!regex.test(mimeType)) { | |
return this.createError('any.image', { v: value }, state, options); | |
} | |
return value; | |
} | |
}, | |
{ | |
name: 'isJS', | |
validate(params, value, state, options) { | |
const mimeType = value.hapi.headers['content-type']; | |
if (mimeType !== 'application/javascript') { | |
return this.createError('any.isJS', { v: value }, state, options); | |
} | |
return value; | |
} | |
}, | |
{ | |
name: 'isJSON', | |
validate(params, value, state, options) { | |
const mimeType = value.hapi.headers['content-type']; | |
if (mimeType !== 'application/json') { | |
return this.createError('any.isJSON', { v: value }, state, options); | |
} | |
return value; | |
} | |
} | |
] | |
} | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment