UNPKG

2.4 kBJavaScriptView Raw
1"use strict";
2
3const {
4 parse,
5 validate,
6 execute
7} = require(`graphql`);
8
9const {
10 debounce
11} = require(`lodash`);
12
13const withResolverContext = require(`../schema/context`);
14
15const {
16 LocalNodeModel
17} = require(`../schema/node-model`);
18
19class GraphQLRunner {
20 constructor(store) {
21 this.store = store;
22
23 const nodeStore = require(`../db/nodes`);
24
25 const createPageDependency = require(`../redux/actions/add-page-dependency`);
26
27 const {
28 schema,
29 schemaCustomization
30 } = this.store.getState();
31 this.nodeModel = new LocalNodeModel({
32 nodeStore,
33 schema,
34 schemaComposer: schemaCustomization.composer,
35 createPageDependency
36 });
37 this.schema = schema;
38 this.parseCache = new Map();
39 this.validDocuments = new WeakSet();
40 this.scheduleClearCache = debounce(this.clearCache.bind(this), 5000);
41 }
42
43 clearCache() {
44 this.parseCache.clear();
45 this.validDocuments = new WeakSet();
46 }
47
48 parse(query) {
49 if (!this.parseCache.has(query)) {
50 this.parseCache.set(query, parse(query));
51 }
52
53 return this.parseCache.get(query);
54 }
55
56 validate(schema, document) {
57 if (!this.validDocuments.has(document)) {
58 const errors = validate(schema, document);
59
60 if (!errors.length) {
61 this.validDocuments.add(document);
62 }
63
64 return errors;
65 }
66
67 return [];
68 }
69
70 query(query, context) {
71 const {
72 schema,
73 schemaCustomization
74 } = this.store.getState();
75
76 if (this.schema !== schema) {
77 this.schema = schema;
78 this.clearCache();
79 }
80
81 const document = this.parse(query);
82 const errors = this.validate(schema, document);
83 const result = errors.length > 0 ? {
84 errors
85 } : execute({
86 schema,
87 document,
88 rootValue: context,
89 contextValue: withResolverContext({
90 schema,
91 schemaComposer: schemaCustomization.composer,
92 context,
93 customContext: schemaCustomization.context,
94 nodeModel: this.nodeModel
95 }),
96 variableValues: context
97 }); // Queries are usually executed in batch. But after the batch is finished
98 // cache just wastes memory without much benefits.
99 // TODO: consider a better strategy for cache purging/invalidation
100
101 this.scheduleClearCache();
102 return Promise.resolve(result);
103 }
104
105}
106
107module.exports = GraphQLRunner;
108//# sourceMappingURL=graphql-runner.js.map
\No newline at end of file