1 | import { GraphQLSchema, GraphQLObjectType, extendSchema, parse } from 'graphql'
|
2 | import { addResolveFunctionsToSchema } from 'graphql-tools'
|
3 | import { lookup, browse, search } from './queries'
|
4 | import { nodeField } from './types/node'
|
5 |
|
6 | const debug = require('debug')('graphbrainz:schema')
|
7 |
|
8 | export 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 |
|
35 | if (outputSchema._queryType.description === undefined) {
|
36 | outputSchema._queryType.description = schema._queryType.description
|
37 | }
|
38 | return outputSchema
|
39 | }
|
40 |
|
41 | export 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 |
|
48 | export default new GraphQLSchema({
|
49 | query: new GraphQLObjectType({
|
50 | name: 'Query',
|
51 | description: `The query root, from which multiple types of MusicBrainz
|
52 | requests can be made.`,
|
53 | fields: () => ({
|
54 | lookup,
|
55 | browse,
|
56 | search,
|
57 | node: nodeField
|
58 | })
|
59 | })
|
60 | })
|