Skip to content

fabrix-app/spool-joi

Repository files navigation

spool-joi

Gitter NPM version Build Status Test Coverage Dependency Status Follow @FabrixApp on Twitter

📦 Joi Spool

A Spool to extend Fabrix with a unified validator for use in other spools and applications.

Joi is the most powerful validator for javascript, and making it a spool make it easy to use the same joi validator module in all of your other spools and applications.

Install

$ npm install --save @fabrix/spool-joi

Configure

// config/main.ts
import { joiSpool } from '@fabrix/spool-joi'
export const main = {
  spools: [
    // ... other spools
    joiSpool
  ]
}

Configuration

// config/joi.ts
export const joi = {
}

For more information about store (type and configuration) please see the joi documentation.

Usage

// Create some data to validate
const data = 'key'

// Make a conveince const 
const joi = this.app.validator

// Create a Schema just like you would with joi
const schema = joi.alternatives().try(
  joi.string().valid('key'),
  joi.number().valid(5),
  joi.object({
    a: joi.boolean().valid(true)
  })
)

// Validate the data against the schema
this.app.validate(data, schema)
  .then(res => {
    // Do something with the valid object
  })
  .catch(err => {
    // Do something with the error
  })


// Optionally, you can pass a callback as well  
this.app.validate(data, schema, (error, value) => {
  if (error) {
    // Do somethign with the error
  }
  // Do something with the valid value
})