Created
April 20, 2016 10:25
-
-
Save offlinehacker/461d0df9b7f8582524f8dfe1338165f0 to your computer and use it in GitHub Desktop.
This file contains 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
// npm install hapijs/joi#issue-577 | |
'use strict'; | |
var Joi = require('joi'); | |
class TypableObject extends Object { | |
constructor(value, type) { | |
super(value); | |
Object.defineProperty(this, '_type', {value: type}); | |
} | |
} | |
class TypableArray extends Object { | |
constructor(value, type) { | |
super(value); | |
Object.defineProperty(this, '_type', {value: type}); | |
} | |
} | |
class TypableNumber extends Number { | |
constructor(value, type) { | |
super(value); | |
Object.defineProperty(this, '_type', {value: type}); | |
} | |
} | |
class TypableString extends String { | |
constructor(value, type) { | |
super(value); | |
Object.defineProperty(this, '_type', {value: type}); | |
} | |
} | |
class TypableBoolean extends Boolean { | |
constructor(value, type) { | |
super(value); | |
Object.defineProperty(this, '_type', {value: type}); | |
} | |
} | |
class TypableDate extends Date { | |
constructor(value, type) { | |
super(value); | |
Object.defineProperty(this, '_type', {value: type}); | |
} | |
} | |
function typableValidator(typeName, type) { | |
return { | |
base: Joi[typeName](), | |
pre(value, state, options) { | |
return new type(value, this._flags.type); | |
}, | |
rules: [{ | |
name: 'type', | |
params: { | |
type: Joi.string().required() | |
}, | |
setup(params) { | |
this._flags.type = params.type; | |
} | |
}], | |
name: typeName | |
}; | |
} | |
const customJoi = Joi | |
.extend(typableValidator('array', TypableArray)) | |
.extend(typableValidator('object', TypableObject)) | |
.extend(typableValidator('number', TypableNumber)) | |
.extend(typableValidator('string', TypableString)) | |
.extend(typableValidator('boolean', TypableBoolean)) | |
.extend(typableValidator('date', TypableDate)); | |
const schema = customJoi.alternatives().try([ | |
customJoi.string().type("stringtype"), | |
customJoi.array().items(customJoi.object().keys({ | |
a: customJoi.number().required().type('numbertype'), | |
b: customJoi.boolean().required().type('booleantype'), | |
c: customJoi.date().type('datetype') | |
}).type('objecttype')).type('arraytype') | |
]) | |
const result = schema.validate([{a: 1234, b: false, c: '12-21-2012'}]); | |
const result2 = schema.validate("abcd"); | |
console.log(result.value._type); | |
console.log(result.value.valueOf()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment