Skip to content

Instantly share code, notes, and snippets.

@damiancipolat
Created June 11, 2019 03:00
Show Gist options
  • Save damiancipolat/da3962ea91b5121c5d2ded40da9f8969 to your computer and use it in GitHub Desktop.
Save damiancipolat/da3962ea91b5121c5d2ded40da9f8969 to your computer and use it in GitHub Desktop.
Create a joi decorator function that dinamycali extend the validations.
//Include joi module schema validator.
const Joi = require('joi');
/*
Receive a js structure using joi values and return it as a joi object with keys.
Params:
schema : {strucutre}
Returns:
{Joi object}
*/
const base = (schema) => Joi.object().keys(schema);
/*
Receive a joi schema object and add unknow property to allow fields don't declared in the schema.
Params:
schema : {Joi object}
Returns:
{Joi object}
*/
const unknown = (schema) => schema.unknown(true);
/*
Receive a joi object - keys and return the key list.
Params:
schema : {Joi object}
Returns:
[string]
*/
const getKeys = (schema) => (schema&&schema._inner.children)
? schema._inner.children.map(elem => elem.key)
: [];
/*
Receive a joi schema that add a 'or' validation, allow one or more field of the structure.
Params:
schema : {Joi object}
Returns:
{Joi object}
*/
const partial = (schema) => schema.or(getKeys(schema));
/*
Receive a joi schema that add a 'and' validation, allow all the field of the structure in the param.
Params:
schema : {Joi object}
Returns:
{Joi object}
*/
const mandatory = (schema) => schema.with(getKeys(schema));
/*
Validate a joi structure and return a promise.
Params:
schema : {Joi object}
myObj : {js flat structure}
Returns:
promise
*/
const validate = async (myObj,schema)=> await Joi.validate(myObj, schema);
/*
Create a partial validation and validate it.
Params:
schema : {Joi object}
Obj : {js flat structure}
Returns:
promise
*/
const partialValidation = (obj,schema) => validate(obj,unknown(partial(schema)));
/*
Create a complete validation and validate it.
Params:
schema : {Joi object}
Obj : {js flat structure}
Returns:
promise
*/
const completeValidation = (obj,schema) => validate(obj,unknown(partial(schema)));
/* -------------------
EXAMPLE
-------------------- */
//Define a custom schema.
let schema = Joi.object().keys({
username : Joi.string().alphanum(),
password : Joi.string().regex(/^[a-zA-Z0-9]{6,16}$/).min(6),
dni: Joi.number(),
single: Joi.boolean(),
email:Joi.string().email(),
cbu:Joi.string()
});
const peter = {
opa:'aaa',
sex:true,
dni:33295515
};
partialValidation(peter,schema)
.then((ok)=>console.log('ok PARTIAL'))
.catch((err)=>console.log('error>>',err));
completeValidation(peter,schema)
.then((ok)=>console.log('ok COMPLETE'))
.catch((err)=>console.log('error>>',err));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment