From 5f0a23d8deaaa745a2210e2fd42d3d7dfc7ffcee Mon Sep 17 00:00:00 2001 From: Joseph Savona Date: Fri, 27 Nov 2015 16:17:16 -0800 Subject: [PATCH] Skip printing empty fragments --- .../__tests__/printRelayOSSQuery-test.js | 24 +++++++++++++++++++ src/traversal/printRelayOSSQuery.js | 19 +++++++++++---- 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/src/__forks__/traversal/__tests__/printRelayOSSQuery-test.js b/src/__forks__/traversal/__tests__/printRelayOSSQuery-test.js index c1554173781c8..d4aa3c56919e1 100644 --- a/src/__forks__/traversal/__tests__/printRelayOSSQuery-test.js +++ b/src/__forks__/traversal/__tests__/printRelayOSSQuery-test.js @@ -288,6 +288,30 @@ describe('printRelayOSSQuery', () => { `); expect(variables).toEqual({}); }); + + it('omits empty inline fragments', () => { + var fragment = getNode(Relay.QL` + fragment on Viewer { + actor { + id + } + ... on Viewer { + actor @include(if: $false) { + name + } + } + } + `, {false: false}); + var {text} = printRelayOSSQuery(fragment); + expect(text).toEqualPrintedQuery(` + fragment PrintRelayOSSQuery on Viewer { + actor { + id, + __typename + } + } + `); + }); }); describe('fields', () => { diff --git a/src/traversal/printRelayOSSQuery.js b/src/traversal/printRelayOSSQuery.js index b5e82df856191..6e8b34ab7eb7d 100644 --- a/src/traversal/printRelayOSSQuery.js +++ b/src/traversal/printRelayOSSQuery.js @@ -160,7 +160,10 @@ function printFragment( function printInlineFragment( node: RelayQuery.Fragment, printerState: PrinterState -): string { +): ?string { + if (!node.getChildren().length) { + return null; + } var fragmentID = node.getFragmentID(); var {fragmentMap} = printerState; if (!(fragmentID in fragmentMap)) { @@ -210,9 +213,11 @@ function printChildren( node: RelayQuery.Node, printerState: PrinterState ): string { - var children = node.getChildren().map(node => { + let children; + node.getChildren().forEach(node => { if (node instanceof RelayQuery.Field) { - return printField(node, printerState); + children = children || []; + children.push(printField(node, printerState)); } else { invariant( node instanceof RelayQuery.Fragment, @@ -220,10 +225,14 @@ function printChildren( '`Fragment`, got `%s`.', node.constructor.name ); - return printInlineFragment(node, printerState); + const printedFragment = printInlineFragment(node, printerState); + if (printedFragment) { + children = children || []; + children.push(printedFragment); + } } }); - if (!children.length) { + if (!children) { return ''; } return '{' + children.join(',') + '}';