Skip to content

Commit

Permalink
Skip printing empty fragments
Browse files Browse the repository at this point in the history
Summary: Fragments can be empty if all non-generated fields are skipped due to `include` or `skip` directives - these shouldn't be printed.
Closes #634

Reviewed By: yungsters

Differential Revision: D2701245

fb-gh-sync-id: dc4cbf9176e46a9ecd23311fb31c40bcc9d3e385
  • Loading branch information
josephsavona authored and facebook-github-bot-4 committed Nov 28, 2015
1 parent b9a17a3 commit 320522d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
24 changes: 24 additions & 0 deletions src/__forks__/traversal/__tests__/printRelayOSSQuery-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
19 changes: 14 additions & 5 deletions src/traversal/printRelayOSSQuery.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down Expand Up @@ -210,20 +213,26 @@ 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,
'printRelayOSSQuery(): expected child node to be a `Field` or ' +
'`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(',') + '}';
Expand Down

0 comments on commit 320522d

Please sign in to comment.