-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
99 lines (85 loc) · 3.12 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
'use strict'
const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const {
makeExecutableSchema,
} = require('graphql-tools');
const gql = require('graphql-tag');
const {execute, formatError} = require('graphql');
const defaultSchemasFileDir = "schemas";
const defaultResolverFileDir = "resolvers";
const defaultSchemaFileExt = ".graphqls";
const defaultResolverFileExt = ".js";
const defaultAllQueryFileName = "query.graphqls";
class EasyGraphQL {
constructor (basePath) {
const subDirs = fs.readdirSync(basePath);
const allSchemas = [];
const allResolversMap = {};
// entity schema
const schemaDir = path.join(basePath, defaultSchemasFileDir);
const schemaFiles = fs.readdirSync(schemaDir);
schemaFiles.forEach(filename => {
if (path.extname(filename).toLowerCase() === defaultSchemaFileExt) {
const schemaFileName = path.join(basePath, defaultSchemasFileDir, filename);
const schemaContent = fs.readFileSync(schemaFileName, {encoding: 'utf8'});
allSchemas.push(schemaContent);
}
});
// all query
const queryFileName = path.join(basePath, defaultAllQueryFileName);
if (fs.existsSync(queryFileName)) {
const queryContent = fs.readFileSync(queryFileName, {encoding: 'utf8'});
allSchemas.push(queryContent);
}
// resolver
const resolverDir = path.join(basePath, defaultResolverFileDir);
const resolverFiles = fs.readdirSync(resolverDir);
resolverFiles.forEach(filename => {
if (path.extname(filename).toLowerCase() === defaultResolverFileExt) {
const resolverFileName = path.join(basePath, defaultResolverFileDir, filename);
const resolveContent = require(resolverFileName);
_.merge(allResolversMap, resolveContent);
}
});
this._schema = makeExecutableSchema({
typeDefs: allSchemas,
resolvers: allResolversMap,
});
}
getSchema () {
return this._schema;
}
/**
* do the GraphQL query execute
* @param {*} requestObj - GraphQL query object {query: "..."}
* @param {*} context - [optional] query context
* @returns {Promise} - GraphQL execute promise
*/
queryGraphQLAsync (requestObj, {context}) {
return new Promise((resolve, reject) => {
const {query, variables, operationName} = requestObj;
const queryAST = gql`${query}`;
const schema = this._schema;
execute(
schema,
queryAST,
null,
context,
variables,
operationName
).then(result => {
if (result && result.errors) {
reject(result.errors);
return;
}
resolve(result);
}).catch(err => {
reject(err);
return;
});
});
}
}
module.exports = EasyGraphQL;