UNPKG

2.14 kBJavaScriptView Raw
1import { GraphQLSchema, GraphQLObjectType, extendSchema, parse } from 'graphql'
2import { addResolveFunctionsToSchema } from 'graphql-tools'
3import { lookup, browse, search } from './queries'
4import { nodeField } from './types/node'
5
6const debug = require('debug')('graphbrainz:schema')
7
8export function applyExtension (extension, schema, options = {}) {
9 let outputSchema = schema
10 if (extension.extendSchema) {
11 if (typeof extension.extendSchema === 'object') {
12 debug(`Extending schema via an object from the “${extension.name}” extension.`)
13 const { schemas = [], resolvers } = extension.extendSchema
14 outputSchema = schemas.reduce((updatedSchema, extensionSchema) => {
15 if (typeof extensionSchema === 'string') {
16 extensionSchema = parse(extensionSchema)
17 }
18 return extendSchema(updatedSchema, extensionSchema)
19 }, outputSchema)
20 if (resolvers) {
21 addResolveFunctionsToSchema(outputSchema, resolvers)
22 }
23 } else if (typeof extension.extendSchema === 'function') {
24 debug(`Extending schema via a function from the “${extension.name}” extension.`)
25 outputSchema = extension.extendSchema(schema, options)
26 } else {
27 throw new Error(
28 `The “${extension.name}” extension contains an invalid ` +
29 `\`extendSchema\` value: ${extension.extendSchema}`
30 )
31 }
32 }
33
34 // Fix for `graphql-tools` creating a new Query type with no description.
35 if (outputSchema._queryType.description === undefined) {
36 outputSchema._queryType.description = schema._queryType.description
37 }
38 return outputSchema
39}
40
41export function createSchema (schema, options = {}) {
42 const extensions = options.extensions || []
43 return extensions.reduce((updatedSchema, extension) => {
44 return applyExtension(extension, updatedSchema, options)
45 }, schema)
46}
47
48export default new GraphQLSchema({
49 query: new GraphQLObjectType({
50 name: 'Query',
51 description: `The query root, from which multiple types of MusicBrainz
52requests can be made.`,
53 fields: () => ({
54 lookup,
55 browse,
56 search,
57 node: nodeField
58 })
59 })
60})