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

Add ast toString returning query string #214

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
var parser = require('graphql/language/parser');
var printer = require('graphql/language/printer');

var parse = parser.parse;
var print = printer.print;

// Strip insignificant whitespace
// Note that this could do a lot more, such as reorder fields etc.
Expand Down Expand Up @@ -135,6 +137,7 @@ function parseDocument(doc) {
// existing fragments of the same name
parsed = processFragments(parsed);
parsed = stripLoc(parsed, false);
parsed.toString = function() { return print(this); };
docCache[cacheKey] = parsed;

return parsed;
Expand Down
17 changes: 17 additions & 0 deletions test/graphql.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const gqlRequire = require('../src');
const gqlDefault = require('../src').default;
const loader = require('../loader');
const assert = require('chai').assert;
const print = require('graphql/language/printer').print;

[gqlRequire, gqlDefault].forEach((gql, i) => {
describe(`gql ${i}`, () => {
Expand Down Expand Up @@ -438,6 +439,22 @@ const assert = require('chai').assert;
});
});

it('returned ast toString returns query string', () => {
const query = `{ user(id: 5) { firstName lastName } }`;
const doc = gql(query);

assert.equal(doc.toString(), print(doc));
});

it('returned ast toString returns updated query string after ast mutation', () => {
const query = `{ user(id: 5) { firstName lastName } }`;
const doc = gql(query);

assert.equal(doc.toString().includes('user'), true);
doc.definitions[0].selectionSet.selections[0].name.value = 'employee';
assert.equal(doc.toString().includes('employee'), true);
});

// How to make this work?
// it.only('can reference a fragment passed as a document via shorthand', () => {
// const ast = gql`
Expand Down