Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Webpack: support multiple query definitions per query file #122

Merged
merged 6 commits into from
Dec 6, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 124 additions & 2 deletions loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,133 @@ function expandImports(source, doc) {
module.exports = function(source) {
this.cacheable();
const doc = gql`${source}`;
const outputCode = `
let headerCode = `
var doc = ${JSON.stringify(doc)};
doc.loc.source = ${JSON.stringify(doc.loc.source)};
`;

let outputCode = "";

// Allow multiple query/mutation definitions in a file. This parses out dependencies
// at compile time, and then uses those at load time to create minimal query documents
// We cannot do the latter at compile time due to how the #import code works.
let operationCount = doc.definitions.reduce(function(accum, op) {
if (op.kind === "OperationDefinition") {
return accum + 1;
}

return accum;
}, 0);

if (operationCount <= 1) {
outputCode += `
module.exports = doc;
`
} else {
outputCode +=`
// Collect any fragment/type references from a node, adding them to the refs Set
function collectFragmentReferences(node, refs) {
if (node.kind === "FragmentSpread") {
refs.add(node.name.value);
} else if (node.kind === "VariableDefinition") {
var type = node.type;
if (type.kind === "NamedType") {
refs.add(type.name.value);
}
}

if (node.selectionSet) {
node.selectionSet.selections.forEach(function(selection) {
collectFragmentReferences(selection, refs);
});
}

if (node.variableDefinitions) {
node.variableDefinitions.forEach(function(def) {
collectFragmentReferences(def, refs);
});
}

if (node.definitions) {
node.definitions.forEach(function(def) {
collectFragmentReferences(def, refs);
});
}
}

var definitionRefs = {};
(function extractReferences() {
doc.definitions.forEach(function(def) {
if (def.name) {
var refs = new Set();
collectFragmentReferences(def, refs);
definitionRefs[def.name.value] = refs;
}
});
})();

function findOperation(doc, name) {
return doc.definitions.find(function(op) {
return op.name ? op.name.value == name : false;
});
}

function oneQuery(doc, operationName) {
// Copy the DocumentNode, but clear out the definitions
var newDoc = Object.assign({}, doc);

var op = findOperation(doc, operationName);
newDoc.definitions = [op];

// Now, for the operation we're running, find any fragments referenced by
// it or the fragments it references
var opRefs = definitionRefs[operationName] || new Set();
var allRefs = new Set();
var newRefs = new Set(opRefs);
while (newRefs.size > 0) {
var prevRefs = newRefs;
newRefs = new Set();

prevRefs.forEach(function(refName) {
if (!allRefs.has(refName)) {
allRefs.add(refName);
var childRefs = definitionRefs[refName] || new Set();
childRefs.forEach(function(childRef) {
newRefs.add(childRef);
});
}
});
}

allRefs.forEach(function(refName) {
var op = findOperation(doc, refName);
if (op) {
newDoc.definitions.push(op);
}
});

return newDoc;
}

module.exports = doc;
`

for (const op of doc.definitions) {
if (op.kind === "OperationDefinition") {
if (!op.name) {
throw "Query/mutation names are required for a document with multiple definitions";
}

const opName = op.name.value;
outputCode += `
module.exports["${opName}"] = oneQuery(doc, "${opName}");
`
}
}
}

const importOutputCode = expandImports(source, doc);
const allCode = headerCode + os.EOL + importOutputCode + os.EOL + outputCode + os.EOL;

return outputCode + os.EOL + importOutputCode + os.EOL + `module.exports = doc;`;
return allCode;
};
133 changes: 133 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,98 @@ const assert = require('chai').assert;
assert.equal(module.exports.kind, 'Document');
});

it('parses multiple queries through webpack loader', () => {
const jsSource = loader.call({ cacheable() {} }, `
query Q1 { testQuery }
query Q2 { testQuery2 }
`);
const module = { exports: undefined };
eval(jsSource);

assert.exists(module.exports.Q1);
assert.exists(module.exports.Q2);
assert.equal(module.exports.Q1.kind, 'Document');
assert.equal(module.exports.Q2.kind, 'Document');
assert.equal(module.exports.Q1.definitions.length, 1);
assert.equal(module.exports.Q2.definitions.length, 1);
});

it('tracks fragment dependencies from multiple queries through webpack loader', () => {
const jsSource = loader.call({ cacheable() {} }, `
fragment F1 on F { testQuery }
fragment F2 on F { testQuery2 }
fragment F3 on F { testQuery3 }
query Q1 { ...F1 }
query Q2 { ...F2 }
query Q3 {
...F1
...F2
}
`);
const module = { exports: undefined };
eval(jsSource);

assert.exists(module.exports.Q1);
assert.exists(module.exports.Q2);
assert.exists(module.exports.Q3);
const Q1 = module.exports.Q1.definitions;
const Q2 = module.exports.Q2.definitions;
const Q3 = module.exports.Q3.definitions;

assert.equal(Q1.length, 2);
assert.equal(Q1[0].name.value, 'Q1');
assert.equal(Q1[1].name.value, 'F1');

assert.equal(Q2.length, 2);
assert.equal(Q2[0].name.value, 'Q2');
assert.equal(Q2[1].name.value, 'F2');

assert.equal(Q3.length, 3);
assert.equal(Q3[0].name.value, 'Q3');
assert.equal(Q3[1].name.value, 'F1');
assert.equal(Q3[2].name.value, 'F2');

});

it('tracks fragment dependencies across nested fragments', () => {
const jsSource = loader.call({ cacheable() {} }, `
fragment F11 on F { testQuery }
fragment F22 on F {
...F11
testQuery2
}
fragment F33 on F {
...F22
testQuery3
}

query Q1 {
...F33
}

query Q2 {
id
}
`);

const module = { exports: undefined };
eval(jsSource);

assert.exists(module.exports.Q1);
assert.exists(module.exports.Q2);

const Q1 = module.exports.Q1.definitions;
const Q2 = module.exports.Q2.definitions;

assert.equal(Q1.length, 4);
assert.equal(Q1[0].name.value, 'Q1');
assert.equal(Q1[1].name.value, 'F33');
assert.equal(Q1[2].name.value, 'F22');
assert.equal(Q1[3].name.value, 'F11');

assert.equal(Q2.length, 1);
});

it('correctly imports other files through the webpack loader', () => {
const query = `#import "./fragment_definition.graphql"
query {
Expand All @@ -70,6 +162,47 @@ const assert = require('chai').assert;
assert.equal(definitions[1].kind, 'FragmentDefinition');
});

it('tracks fragment dependencies across fragments loaded via the webpack loader', () => {
const query = `#import "./fragment_definition.graphql"
fragment F111 on F {
...F222
}

query Q1 {
...F111
}

query Q2 {
a
}
`;
const jsSource = loader.call({ cacheable() {} }, query);
const oldRequire = require;
const module = { exports: undefined };
const require = (path) => {
assert.equal(path, './fragment_definition.graphql');
return gql`
fragment F222 on F {
f1
f2
}`;
};
eval(jsSource);

assert.exists(module.exports.Q1);
assert.exists(module.exports.Q2);

const Q1 = module.exports.Q1.definitions;
const Q2 = module.exports.Q2.definitions;

assert.equal(Q1.length, 3);
assert.equal(Q1[0].name.value, 'Q1');
assert.equal(Q1[1].name.value, 'F111');
assert.equal(Q1[2].name.value, 'F222');

assert.equal(Q2.length, 1);
});

it('does not complain when presented with normal comments', (done) => {
assert.doesNotThrow(() => {
const query = `#normal comment
Expand Down