eldoy / waveorb

Javascript web app development framework

Home Page:https://waveorb.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Validation from scripts

eldoy opened this issue · comments

We currently have support for validations as objects in validations. These can be used in the request cycle with $.validate.

How do we use them in scripts, outside the request cycle?

$.validate currently throws (halt), we just want to get the errors. If I want to validate some data:

var { validate } = require('waveorb')
var values = { name: 'Baner', email: 'e@xample.com' }
var validator = await validate(app.validations.userCreate, { values })
if (validator.errors) {
  // handle errors
} else {
  // No errors, empty object
}

This cannot use waveorb-validations at the moment, since it depends on $.

If we are actually saving data after this, it feels more natural to use a classic ORM maybe:

var { validate } = require('waveorb')

class Project {
  constructor (values) {
    this.values = values
  }

  valid() {
    var validator = await validate(app.validations.userCreate, { values: this.values })
    return !!validator.errors
  }
}

We could also introduce a validator function which handles the setup:

var { validate } = require('waveorb')

module.exports = function userCreateValidator($, validation, data) {
  if (!$.db && typeof global.db != 'undefined') $.db = global.db
  if (!$.params) $.params = {}
  // ... Add missing stuff for waveorb-validator and '$'

  return validate($, data)(validation)
}

Added a validator function to app.validator