Last active
February 5, 2016 02:24
-
-
Save swashcap/653bfe4107a7e68c94a7 to your computer and use it in GitHub Desktop.
Thin JOI Classes
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
/** | |
* @module base.js - COINSTAC Model | |
*/ | |
'use strict'; | |
const assign = require('lodash/assign'); | |
const joi = require('joi'); | |
const pick = require('lodash/pick'); | |
/** | |
* @class Base | |
* | |
* @example <caption>Extending Base</caption> | |
* // my-class.js | |
* const Base = require('./path/to/base.js'); | |
* const util = require('util'); | |
* const joi = require('joi'); | |
* | |
* function MyClass(attributes) { | |
* // Call `Base` with `MyClass`’s arguments: | |
* Base.apply(this, arguments); | |
* } | |
* | |
* // Use Node's built-in inheritance: | |
* util.inherits(Base, MyClass); | |
* | |
* // Define `MyClass`’s `schema` on its prototype: | |
* MyClass.prototype.schema = { | |
* data: joi.object().required(), | |
* myString: joi.string().default('my-string'), | |
* myInteger: joi.string().integer().positive(), | |
* }; | |
* | |
* module.exports = MyClass; | |
* | |
* @param {object} attributes | |
*/ | |
function Base(attributes) { | |
assign(this, this.validate(attributes)); | |
}; | |
/** | |
* Get schema. | |
* | |
* @returns {object} | |
*/ | |
Base.prototype.getSchema = function() { | |
return assign({}, this.schema, Base.prototype.schema); | |
} | |
/** | |
* Base class's schema. | |
* | |
* @type {object} | |
*/ | |
Base.prototype.schema = { | |
_id: joi.string(), | |
}; | |
/** | |
* Serialize model. | |
* | |
* @returns {object} | |
*/ | |
Base.prototype.serialize = function() { | |
return pick(this, Object.keys(this.getSchema)); | |
}; | |
/** | |
* To JSON. | |
* | |
* @returns {string} | |
*/ | |
Base.prototype.toJSON = function() { | |
return JSON.stringify(this.serialize()); | |
}; | |
/** | |
* Validate based on sub-class's schema. | |
* {@link https://github.com/hapijs/joi/blob/v7.2.3/API.md#validatevalue-schema-options-callback} | |
* | |
* @param {object} attributes | |
* @returns {object} Validated attributes | |
*/ | |
Base.prototype.validate = function(attributes) { | |
if (typeof attributes === 'undefined') { | |
attributes = {}; | |
} | |
const result = joi.validate( | |
attributes, | |
this.getSchema(), | |
{ convert: false } | |
); | |
if (result.error) { | |
throw new Error(result.error); | |
} | |
return result.value; | |
}; | |
module.exports = Base; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment