Skip to content

Commit

Permalink
Comment the code a bit to explain the approach. Add npmignore
Browse files Browse the repository at this point in the history
  • Loading branch information
leoasis committed Nov 30, 2017
1 parent 21d6dcf commit 54fb252
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
2 changes: 2 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
example
yarn.lock
18 changes: 17 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ const { ExtractGQL } = require('persistgraphql/lib/src/ExtractGQL');
const queryTransformers = require('persistgraphql/lib/src/queryTransformers');
const loadModuleRecursively = require('./load-module-recursively');

module.exports = function graphQLpersistedDocumentLoader(content) {
module.exports = function graphQLPersistedDocumentLoader(content) {
const deps = [];
const context = this;
const options = loaderUtils.getOptions(this) || {};

// Create a fake sandbox to intercept the query dependencies when
// executing the generated code from the graphql-tag loader.
const sandbox = {
require(file) {
deps.push(new Promise((resolve, reject) => {
Expand All @@ -27,24 +29,38 @@ module.exports = function graphQLpersistedDocumentLoader(content) {
exports: null
}
};
// Run the graphql-tag loader generated code to capture the dependencies.
vm.runInNewContext(content, sandbox);

// Get the query document source from the exported module, and
// save it so that we can use it from other modules that may depend on
// this one.
const doc = sandbox.module.exports;
this._module._graphQLQuerySource = doc.loc.source.body;

if (deps.length === 0) {
// If no deps, just try to generate the document id from the
// source returned from graphql-tag loader result. This will
// add an id only if the source contains an operation.
content = tryAddDocumentId(options, content, this._module._graphQLQuerySource);
return content;
}

const callback = this.async();

// If we have dependencies, we retrieve their query sources and
// concatenate them with the one from this module, to create the
// full query source.
Promise.all(deps).then((modules) => {
modules.forEach((mod, index) => {
this._module._graphQLQuerySource += mod.module._graphQLQuerySource;
});

try {
// Now that we have all our dependencies' sources concatenated
// with this module's query source, we can send all that to
// generate the document id, if the resulting source
// is for an operation.
content = tryAddDocumentId(options, content, this._module._graphQLQuerySource);
} catch (e) {
callback(e);
Expand Down

0 comments on commit 54fb252

Please sign in to comment.