All files / lib/graphQl joiConverter.js

17.78% Statements 8/45
0% Branches 0/34
0% Functions 0/3
17.78% Lines 8/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 81 82 83 84 85 86 87 88 89 90  1x   1x 1x   1x                                                                       1x                                       1x                                 1x                 1x  
'use strict'
const joiConverter = module.exports = { }
 
const graphQl = require('graphql')
const readTypes = require('./readTypes.js')
 
joiConverter.simpleAttribute = joiScheme => {
  let type = joiScheme._type
  if (type === 'any') {
    // { _valids: { _set: [ 'M', 'F' ] } }
    type = typeof (joiScheme._valids._set || [ ])[0]
  }
  if (type === 'date') {
    type = 'string'
  }
  if (type === 'number') {
    type = 'float'
  }
 
  if (type === 'array') {
    if (joiScheme._inner.items.length === 1) {
      let joinSubType = joiConverter.simpleAttribute(joiScheme._inner.items[0])
 
      if (!joinSubType) {
        throw new Error('Unable to parse Joi type, got ' + JSON.stringify(joiScheme))
      }
 
      return new graphQl.GraphQLList(graphQl.GraphQLString)
    } else {
      throw new Error('Joi arrays must contain a single type')
    }
  }
 
  const uType = type[0].toUpperCase() + type.substring(1)
  type = graphQl[`GraphQL${uType}`]
 
  if (!type) {
    throw new Error('Unable to parse Joi type, got ' + JSON.stringify(joiScheme))
  }
  return type
}
 
joiConverter.swap = (joiScheme, graphQlResources) => {
  let type
  if (!joiScheme._settings) {
    type = joiConverter.simpleAttribute(joiScheme)
  } else {
    let otherType = joiScheme._settings.__one || joiScheme._settings.__many
    otherType = otherType.join(readTypes.UNION_JOIN_CONST)
    type = graphQlResources[otherType]
 
    if (joiScheme._settings.__many) {
      type = new graphQl.GraphQLList(type)
    }
  }
 
  if ((joiScheme._flags || { }).presence === 'required') {
    type = new graphQl.GraphQLNonNull(type)
  }
  return type
}
 
joiConverter.shallowInput = joiScheme => {
  let type
  if (!joiScheme._settings) {
    type = joiConverter.simpleAttribute(joiScheme)
  } else {
    type = oneRelationship
    if (joiScheme._settings.__many) {
      type = manyRelationship
    }
  }
 
  if ((joiScheme._flags || { }).presence === 'required') {
    type = new graphQl.GraphQLNonNull(type)
  }
  return type
}
 
const oneRelationship = new graphQl.GraphQLInputObjectType({
  name: 'oneRelationship',
  fields: {
    id: {
      type: new graphQl.GraphQLNonNull(graphQl.GraphQLString),
      description: 'The UUID of another resource'
    }
  }
})
const manyRelationship = new graphQl.GraphQLList(oneRelationship)