UNPKG

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