From c6cff481075219c2287e9547c00d7f148b6f1ec0 Mon Sep 17 00:00:00 2001 From: "darren.richards" Date: Tue, 25 Sep 2018 08:52:07 -0700 Subject: [PATCH] Add ast toString returning query string --- src/index.js | 3 +++ test/graphql.js | 17 +++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/index.js b/src/index.js index f52711e4..318935f2 100644 --- a/src/index.js +++ b/src/index.js @@ -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. @@ -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; diff --git a/test/graphql.js b/test/graphql.js index 726e3918..b6f9c482 100644 --- a/test/graphql.js +++ b/test/graphql.js @@ -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}`, () => { @@ -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`