-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
86 lines (62 loc) · 2.03 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
const _ = require('lodash');
const utils = require('./utils/stringify');
module.exports = class GraphQLBuilder {
constructor(connection, options) {
this.query = {};
if (connection) {
this.query[connection] = _.pick(options, ['args', 'connections', 'fields'])
}
}
addArgs(path, args = []) {
let connection = this.getConnection(path);
if (!_.isArray(connection.args)) {
throw new Error('Array expected');
}
connection.args = connection.args.concat(args);
}
addConnection(path, connection, { args = [], connections = {}, fields = [] }) {
const basepath = path ? this.getConnection(path) : this.query;
if (!basepath)
throw new Error('Connection not found');
if (!basepath.connections)
basepath.connections = {};
basepath.connections[connection] = { args, connections, fields }
}
getConnection(path) {
path = path.replace(/\./g, '.connections.');
return _.get(this.query, path);
}
buildArgs(args, callable) {
const empty = callable ? '()' : '';
const argsQuery = args.map((value) => utils.stringifyObject(value)).join(',');
return argsQuery ? `(${argsQuery})` : empty;
}
buildFields(fields) {
return fields.join(',');
}
buildConnections(name, { args = [], connections = {}, fields = [], callable = false }) {
if (!name)
return '';
let connectionFields = Object.keys(connections).map((key) => {
return this.buildConnections(key, connections[key]);
});
const fieldsQuery = this.buildFields(fields);
if (fieldsQuery)
connectionFields = connectionFields.concat(fieldsQuery);
return `${name}${this.buildArgs(args, callable)}{${connectionFields.join(',')}}`
}
buildQuery(names) {
let query = '';
names.forEach((key) => {
const values = this.query[key];
query += this.buildConnections(key, values);
});
return `${query}`;
}
stringify() {
const query = this.buildQuery(Object.keys(this.query));
return JSON.stringify({
query: `{${query}}`
});
}
}