Skip to content

Instantly share code, notes, and snippets.

@lukaswilkeer
Last active September 8, 2019 11:39
Show Gist options
  • Save lukaswilkeer/613ebe69e1fd591d11ed1961a54beb65 to your computer and use it in GitHub Desktop.
Save lukaswilkeer/613ebe69e1fd591d11ed1961a54beb65 to your computer and use it in GitHub Desktop.
tiny-validator
const rules = {
'env': {
rule: (value) => rules.env.property.includes(value)
, property: ['production', 'sandbox']
, default: 'sandbox'
, errorMsg: 'Env must be production or sandbox'
},
'email': {
rule: (value) => value ? true : false
, errorMsg: 'Missing e-mail'
checkers: [isEmail, isString]
},
'token': {
rule: (value) => value ? true : false
, errorMsg: 'Missing token'
},
'logging': {
rule: (value) => value ? true : false
, default: false
}
}
module.exports = rules
const mocha = require('mocha')
const chai = require('chai')
const expect = chai.expect
const should = chai.should
const rules = require('./rules.js')
const validate = require('../validate.js')
// Debug consts
const settings = {
email: '[email protected]'
, token: 'ASA98S98AD7WGGD'
, env: 'sandbox'
}
describe('object validation: ', () => {
it('should return a object with the validated data', (done) => {
let result = validate(settings, rules)
expect(result).to.be.a('object')
done()
})
it('should accept default value', (done) => {
let obj = { name: '' }
let name = {
rule: (name) => name ? name : false
, default : 'lukas'
, errorMsg: 'Something happend with name'
}
let rules = { name }
let result = validate(obj, rules)
expect(result[0]).to.be.eql('lukas')
expect(result[0]).to.be.a('string')
done()
})
it('should verify inputed types')
})
describe('list validation: ', () => {
it('should return only validated data')
it('should throw an error when the data does not match')
it('should accept default value')
it('should verify types')
})
describe('checking object:', () => {
it('should return an object {key -> data}', (done) => {
let result = validate(rules, settings)
console.log(result)
expect(result).to.be.a('object')
expect(result).to.have('key')
done()
})
})
const map = require('lodash/fp/map')
const multiValidate = (arr = [], rules) => arr.map(rules)
//const validate = (data, rule) => data.filter(rule.rule) ? data : error(rule.errorMsg)
const verifyDefault = (validator) =>
validator.default
? validator.default
: false
const validate = (data, validator) =>
validator.rule(data)
? data
: verifyDefault(validator)
const match = (rules, obj, result = {}) => (key) =>
rules[key]
? result[key] = validate(rules[key], obj[key], key)
: result[key] = obj[key]
// :: {rules}, {obj} -> {key -> data}
const checkObj = (rules, obj) => {
let check = match(rules, obj)
return map(check, Object.keys(obj))
}
module.exports = checkObj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment