All files / lib ourJoi.js

18.37% Statements 9/49
0% Branches 0/16
0% Functions 0/10
20% Lines 9/45
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80  1x   1x   1x               1x                                         1x                                     1x       1x                       1x                 1x  
'use strict'
const ourJoi = module.exports = { }
 
const Joi = require('joi')
 
ourJoi._joiBase = resourceName => {
  const relationType = Joi.object().keys({
    id: Joi.string().required(),
    type: Joi.any().required().valid(resourceName),
    meta: Joi.object().optional()
  })
  return relationType
}
Joi.one = function () {
  const resources = Array.prototype.slice.call(arguments)
  resources.forEach(resource => {
    if (typeof resource !== 'string') throw new Error('Expected a string when defining a primary relation via .one()')
  })
  const obj = Joi.alternatives().try([
    Joi.any().valid(null) // null
  ].concat(resources.map(ourJoi._joiBase)))
  obj._settings = {
    __one: resources
  }
  obj._settings._uidType = 'string'
  obj.uidType = function (keyType) {
    if (keyType !== 'uuid' && keyType !== 'autoincrement') {
      throw new Error('Resources can be related only via UUID or AUTOINCREMENT keys')
    }
    obj._settings._uidType = keyType
    return obj
  }
  return obj
}
Joi.many = function () {
  const resources = Array.prototype.slice.call(arguments)
  resources.forEach(resource => {
    if (typeof resource !== 'string') throw new Error('Expected a string when defining a primary relation via .many()')
  })
  const obj = Joi.array().items(resources.map(ourJoi._joiBase))
  obj._settings = {
    __many: resources
  }
  obj._settings._uidType = 'string'
  obj.uidType = function (keyType) {
    if (keyType !== 'uuid' && keyType !== 'autoincrement') {
      throw new Error('Resources can be related only via UUID or AUTOINCREMENT keys')
    }
    obj._settings._uidType = keyType
    return obj
  }
  return obj
}
Joi._validateForeignRelation = config => {
  if (!config.as) throw new Error("Missing 'as' property when defining a foreign relation")
  if (!config.resource) throw new Error("Missing 'resource' property when defining a foreign relation")
}
Joi.belongsToOne = config => {
  Joi._validateForeignRelation(config)
  const obj = Joi.alternatives().try(
    Joi.any().valid(null), // null
    ourJoi._joiBase(config.resource)
  )
  obj._settings = {
    __one: [ config.resource ],
    __as: config.as
  }
  return obj
}
Joi.belongsToMany = config => {
  Joi._validateForeignRelation(config)
  const obj = Joi.array().items(ourJoi._joiBase(config.resource))
  obj._settings = {
    __many: [ config.resource ],
    __as: config.as
  }
  return obj
}
ourJoi.Joi = Joi