/
index.js
216 lines (209 loc) · 6.73 KB
/
index.js
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
//
// Takes an object of { key: JoiSchema } pairs to generate a GraphQL Schema.
//
const Joi = require('joi')
const {
uniqueId,
map,
find,
capitalize,
keys,
isEqual,
assign,
flatten,
isEmpty,
mapValues,
omitBy,
isNull
} = require('lodash')
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
GraphQLFloat,
GraphQLInt,
GraphQLInputObjectType,
GraphQLList,
GraphQLUnionType,
GraphQLBoolean,
GraphQLNonNull
} = require('graphql')
// Convenience helpers to determine a Joi schema's
// "presence", e.g. required or forbidden
const presence = (desc, name) =>
desc.flags &&
desc.flags.presence &&
desc.flags.presence === name
// Cache converted types by their `meta({ name: '' })` property so we
// don't end up with a litter of anonymously generated GraphQL types
const cachedTypes = {}
// Maps a Joi description to a GraphQL type. `isInput` is used to determine
// when to use, say, GraphQLInputObjectType vs. GraphQLObjectType—useful in
// cases such as args and mutations.
const descToType = (desc, isInput) => {
let typeName = (
(isInput ? 'Input' : '') +
(map(desc.meta, 'name')[0] || 'Anon' + uniqueId())
)
const required = isInput && presence(desc, 'required')
const type = {
boolean: () => GraphQLBoolean,
date: () => GraphQLString,
string: () => GraphQLString,
number: () => {
const isInteger = !!find(desc.rules, { name: 'integer' })
return isInteger ? GraphQLInt : GraphQLFloat
},
object: () => {
if (cachedTypes[typeName]) return cachedTypes[typeName]
let type
if (isInput) {
type = new GraphQLInputObjectType({
name: typeName,
description: desc.description,
fields: omitBy(mapValues(desc.children, (child) => {
if (presence(child, 'forbidden')) return null
return { type: descToType(child, true) }
}), isNull)
})
} else {
type = new GraphQLObjectType({
name: typeName,
description: desc.description,
fields: descsToFields(desc.children)
})
}
cachedTypes[typeName] = type
return type
},
array: () => {
let type
const items = desc.items.filter((item) => !presence(item, 'forbidden'))
if (items.length === 1) {
type = descToType(items[0], isInput)
} else {
typeName = map(items, (d) => {
const name = (
(d.meta && capitalize(d.meta.name)) ||
capitalize(d.type) ||
'Anon' + uniqueId()
)
return (isInput ? 'Input' : '') + name
}).join('Or')
if (cachedTypes[typeName]) {
type = cachedTypes[typeName]
} else {
const types = items.map((item) => descToType(item, isInput))
if (isInput) {
const children = items.map((item) => item.children)
const fields = descsToFields(assign(...flatten(children)))
type = new GraphQLInputObjectType({
name: typeName,
description: desc.description,
fields: fields
})
} else {
type = new GraphQLUnionType({
name: typeName,
description: desc.description,
types: types,
// TODO: Should use JOI.validate(), just looks at matching keys
// We might need to pass schema here instead
resolveType: (val) =>
find(map(items, (item, i) =>
isEqual(keys(val), keys(item.children)) && types[i]))
})
}
}
}
if (!cachedTypes[typeName]) cachedTypes[typeName] = type
return new GraphQLList(type)
},
alternatives: () => {
let type
const alternatives = desc.alternatives
.filter((a) => !presence(a, 'forbidden'))
if (cachedTypes[typeName]) return cachedTypes[typeName]
const types = alternatives.map((item) =>
descToType(item, isInput))
const children = alternatives.map((item) => item.children)
const fields = descsToFields(assign(...flatten(children)))
if (isInput) {
type = new GraphQLInputObjectType({
name: typeName,
description: desc.description,
fields: fields
})
} else {
type = new GraphQLUnionType({
name: typeName,
description: desc.description,
types: types,
resolveType: (val) =>
find(map(alternatives, (item, i) => {
const isTypeOf = map(item.meta, 'isTypeOf')[0]
if (isTypeOf) return isTypeOf(val) && types[i]
// TODO: Should use JOI.validate(), just looks at matching keys
// We might need to pass schema here instead
else return isEqual(keys(val), keys(item.children)) && types[i]
}))
})
}
cachedTypes[typeName] = type
return type
}
}[desc.type]()
return required ? new GraphQLNonNull(type) : type
}
// Convert a Joi description's `meta({ args: {} })` to a GraphQL field's
// arguments
const descToArgs = (desc) => {
const argsSchema = map(desc.meta, 'args')[0]
return argsSchema && omitBy(mapValues(argsSchema, (schema) => {
if (presence(schema.describe(), 'forbidden')) return null
return {
type: descToType(schema.describe(), true)
}
}), isNull)
}
// Wraps a resolve function specifid in a Joi schema to add validation.
const validatedResolve = (desc) => (source, args, root, opts) => {
const resolve = desc.meta && desc.meta[0].resolve
if (args && !isEmpty(args)) {
const argsSchema = map(desc.meta, 'args')[0]
const { value, error } = Joi.validate(args, argsSchema)
if (error) throw error
return resolve(source, value, root, opts)
}
if (resolve) return resolve(source, args, root, opts)
else return source && source[opts.fieldASTs[0].name.value]
}
// Convert a hash of descriptions into an object appropriate to put in a
// GraphQL.js `fields` key.
const descsToFields = (descs, resolveMiddlewares = () => {}) =>
omitBy(mapValues(descs, (desc) => {
if (presence(desc, 'forbidden')) return null
return {
type: descToType(desc),
args: descToArgs(desc),
description: desc.description || '',
resolve: validatedResolve(desc)
}
}), isNull)
// Converts the { key: JoiSchema } pairs to a GraphQL.js schema object
module.exports = (jois) => {
const attrs = {}
if (jois.query) {
attrs.query = new GraphQLObjectType({
name: 'RootQueryType',
fields: descsToFields(mapValues(jois.query, (j) => j.describe()))
})
}
if (jois.mutation) {
attrs.mutation = new GraphQLObjectType({
name: 'RootMutationType',
fields: descsToFields(mapValues(jois.mutation, (j) => j.describe()))
})
}
return new GraphQLSchema(attrs)
}