Skip to content

Commit

Permalink
Fix graphql-tag/loader by properly stringifying GraphQL source (#65)
Browse files Browse the repository at this point in the history
[Loc.prototype.toJson](https://github.com/graphql/graphql-js/blob/77f2785e6c740a95e7615dad41e4ac1b663cea0e/src/language/parser.js#L1048-L1050) will never return the `source` key (which holds the stringified version of the query that we need when using the Webpack loader. We'll manually add it since the reference to `source` still exists on `doc.loc`
  • Loading branch information
jnwng authored May 16, 2017
1 parent 63efcac commit d646588
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
5 changes: 4 additions & 1 deletion loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ function expandImports(source, doc) {
module.exports = function(source) {
this.cacheable();
const doc = gql`${source}`;
const outputCode = `var doc = ${JSON.stringify(doc)};`;
const outputCode = `
var doc = ${JSON.stringify(doc)};
doc.loc.source = ${JSON.stringify(doc.loc.source)};
`;
const importOutputCode = expandImports(source, doc);

return outputCode + "\n" + importOutputCode + "\n" + `module.exports = doc;`;
Expand Down
17 changes: 17 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,23 @@ const assert = require('chai').assert;
assert.equal(gql`{ field(input: "${0}") }`.kind, 'Document');
});

it('allows interpolation of documents generated by the webpack loader', () => {
const sameFragment = "fragment SomeFragmentName on SomeType { someField }";

const jsSource = loader.call(
{ cacheable() {} },
"fragment SomeFragmentName on SomeType { someField }"
);
const module = { exports: undefined };
eval(jsSource);

const document = gql`query { ...SomeFragmentName } ${module.exports}`;
assert.equal(document.kind, 'Document');
assert.equal(document.definitions.length, 2);
assert.equal(document.definitions[0].kind, 'OperationDefinition');
assert.equal(document.definitions[1].kind, 'FragmentDefinition');
});

it('parses queries through webpack loader', () => {
const jsSource = loader.call({ cacheable() {} }, '{ testQuery }');
const module = { exports: undefined };
Expand Down

0 comments on commit d646588

Please sign in to comment.