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

Skip printing empty fragments #634

Closed
Closed
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
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