-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathload_schema.js
74 lines (64 loc) · 2.08 KB
/
load_schema.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
'use strict';
const fs = require('fs');
const path = require('path');
const {
makeExecutableSchema,
} = require('graphql-tools');
const _ = require('lodash');
const SYMBOL_SCHEMA = Symbol('Applicaton#schema');
module.exports = app => {
const basePath = path.join(app.baseDir, 'app/graphql');
const types = fs.readdirSync(basePath);
const schemas = [];
const resolverMap = {};
const resolverFactories = [];
const directiveMap = {};
const schemaDirectivesProps = {};
types.forEach(type => {
// Load schema
const schemaFile = path.join(basePath, type, 'schema.graphql');
/* istanbul ignore else */
if (fs.existsSync(schemaFile)) {
const schema = fs.readFileSync(schemaFile, {
encoding: 'utf8',
});
schemas.push(schema);
}
// Load resolver
const resolverFile = path.join(basePath, type, 'resolver.js');
if (fs.existsSync(resolverFile)) {
const resolver = require(resolverFile);
if (_.isFunction(resolver)) {
resolverFactories.push(resolver);
} else if (_.isObject(resolver)) {
_.merge(resolverMap, resolver);
}
}
// Load directive resolver
const directiveFile = path.join(basePath, type, 'directive.js');
if (fs.existsSync(directiveFile)) {
const directive = require(directiveFile);
_.merge(directiveMap, directive);
}
// Load schemaDirectives
let schemaDirectivesFile = path.join(basePath, type, 'schemaDirective.js');
if (fs.existsSync(schemaDirectivesFile)) {
schemaDirectivesFile = require(schemaDirectivesFile);
_.merge(schemaDirectivesProps, schemaDirectivesFile);
}
});
Object.defineProperty(app, 'schema', {
get() {
if (!this[SYMBOL_SCHEMA]) {
resolverFactories.forEach(resolverFactory => _.merge(resolverMap, resolverFactory(app)));
this[SYMBOL_SCHEMA] = makeExecutableSchema({
typeDefs: schemas,
resolvers: resolverMap,
directiveResolvers: directiveMap,
schemaDirectives: schemaDirectivesProps,
});
}
return this[SYMBOL_SCHEMA];
},
});
};