-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
80 lines (63 loc) · 1.86 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
'use strict'
const Trailpack = require('trailpack')
const { buildSchema } = require('graphql')
const graphqlTag = strings => strings.join()
const fs = require('fs')
const path = require('path')
module.exports = class GraphqlTrailpack extends Trailpack {
/**
* Validate GraphQL Schema (attempt to compile schema; fail if error)
*/
validate () {
}
configure () {
const config = this.app.config.graphql
if (config.enableIntrospectionQuery !== false) {
config.enableIntrospectionQuery = true
}
this.schemaFile = path.resolve(this.app.config.main.paths.temp, 'schema.graphql')
}
/**
* Compile graphql schema and resolvers
*/
initialize () {
const models = this.app.models
const gqlModels = Object.keys(models)
.map(k => [ models[k], k ])
.filter(([ model, modelName ]) => {
const config = model.constructor.config()
return config && config.type === 'graphql'
})
const schemaString = gqlModels
.map(([ model, modelName ]) => model.constructor.schema(graphqlTag) || '')
.join('\n')
const rootQueryBody = gqlModels
.map(([ model, modelName ]) => `${modelName.toLowerCase()}: ${modelName}Query`)
.join('\n')
this.schemaString = `
${schemaString}
type Query {
${rootQueryBody}
}
schema {
query: Query
}
`
this.schema = buildSchema(this.schemaString)
this.resolvers = gqlModels
.map(([ model, modelName ]) => {
return {
[modelName.toLowerCase()]: model.constructor.resolver(this.app) || { }
}
})
.reduce((obj, resolver) => Object.assign(obj, resolver), { })
fs.writeFileSync(this.schemaFile, this.schemaString)
}
constructor (app) {
super(app, {
config: require('./config'),
api: require('./api'),
pkg: require('./package')
})
}
}