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

Support includeUnusedVariables option for HttpLink. #7127

Merged
merged 3 commits into from
Oct 6, 2020
Merged
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
72 changes: 67 additions & 5 deletions src/link/http/__tests__/HttpLink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ describe('HttpLink', () => {
uri: '/data',
fetchOptions: { method: 'GET' },
includeExtensions: true,
includeUnusedVariables: true,
});

execute(link, { query: sampleQuery, variables, extensions }).subscribe({
Expand Down Expand Up @@ -138,7 +139,7 @@ describe('HttpLink', () => {
expect(body).toBeUndefined();
expect(method).toBe('GET');
expect(uri).toBe(
'/data?foo=bar&query=query%20SampleQuery%20%7B%0A%20%20stub%20%7B%0A%20%20%20%20id%0A%20%20%7D%0A%7D%0A&operationName=SampleQuery&variables=%7B%22params%22%3A%22stub%22%7D',
'/data?foo=bar&query=query%20SampleQuery%20%7B%0A%20%20stub%20%7B%0A%20%20%20%20id%0A%20%20%7D%0A%7D%0A&operationName=SampleQuery&variables=%7B%7D',
);
}),
error: error => done.fail(error),
Expand All @@ -164,7 +165,7 @@ describe('HttpLink', () => {
expect(body).toBeUndefined();
expect(method).toBe('GET');
expect(uri).toBe(
'/data?query=query%20SampleQuery%20%7B%0A%20%20stub%20%7B%0A%20%20%20%20id%0A%20%20%7D%0A%7D%0A&operationName=SampleQuery&variables=%7B%22params%22%3A%22stub%22%7D',
'/data?query=query%20SampleQuery%20%7B%0A%20%20stub%20%7B%0A%20%20%20%20id%0A%20%20%7D%0A%7D%0A&operationName=SampleQuery&variables=%7B%7D',
);
}),
);
Expand All @@ -187,7 +188,7 @@ describe('HttpLink', () => {
expect(body).toBeUndefined();
expect(method).toBe('GET');
expect(uri).toBe(
'/data?query=query%20SampleQuery%20%7B%0A%20%20stub%20%7B%0A%20%20%20%20id%0A%20%20%7D%0A%7D%0A&operationName=SampleQuery&variables=%7B%22params%22%3A%22stub%22%7D',
'/data?query=query%20SampleQuery%20%7B%0A%20%20stub%20%7B%0A%20%20%20%20id%0A%20%20%7D%0A%7D%0A&operationName=SampleQuery&variables=%7B%7D',
);
}),
);
Expand All @@ -214,6 +215,62 @@ describe('HttpLink', () => {
);
});

it('strips unused variables, respecting nested fragments', done => {
const link = createHttpLink({ uri: '/data' });

const query = gql`
query PEOPLE (
$declaredAndUsed: String,
$declaredButUnused: Int,
) {
people(
surprise: $undeclared,
noSurprise: $declaredAndUsed,
) {
... on Doctor {
specialty(var: $usedByInlineFragment)
}
...LawyerFragment
}
}
fragment LawyerFragment on Lawyer {
caseCount(var: $usedByNamedFragment)
}
`;

const variables = {
unused: 'strip',
declaredButUnused: 'strip',
declaredAndUsed: 'keep',
undeclared: 'keep',
usedByInlineFragment: 'keep',
usedByNamedFragment: 'keep',
};

execute(link, {
query,
variables,
}).subscribe({
next: makeCallback(done, () => {
const [uri, options] = fetchMock.lastCall()!;
const { method, body } = options!;
expect(JSON.parse(body as string)).toEqual({
operationName: "PEOPLE",
query: print(query),
variables: {
declaredAndUsed: 'keep',
undeclared: 'keep',
usedByInlineFragment: 'keep',
usedByNamedFragment: 'keep',
},
});
expect(method).toBe('POST');
expect(uri).toBe('/data');
}),
error: error => done.fail(error),
});
});

it('should add client awareness settings to request headers', done => {
const variables = { params: 'stub' };
const link = createHttpLink({
Expand Down Expand Up @@ -277,6 +334,7 @@ describe('HttpLink', () => {
const link = createHttpLink({
uri: '/data',
useGETForQueries: true,
includeUnusedVariables: true,
});

let b;
Expand Down Expand Up @@ -422,7 +480,7 @@ describe('HttpLink', () => {
try {
let body = convertBatchedBody(fetchMock.lastCall()![1]!.body);
expect(body.query).toBe(print(sampleMutation));
expect(body.variables).toEqual(variables);
expect(body.variables).toEqual({});
expect(body.context).not.toBeDefined();
if (includeExtensions) {
expect(body.extensions).toBeDefined();
Expand Down Expand Up @@ -1024,7 +1082,11 @@ describe('HttpLink', () => {
});
it("throws if the body can't be stringified", done => {
fetch.mockReturnValueOnce(Promise.resolve({ data: {}, text }));
const link = createHttpLink({ uri: 'data', fetch: fetch as any });
const link = createHttpLink({
uri: 'data',
fetch: fetch as any,
includeUnusedVariables: true,
});

let b;
const a: any = { b };
Expand Down
27 changes: 26 additions & 1 deletion src/link/http/createHttpLink.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { DefinitionNode } from 'graphql';
import { DefinitionNode, VariableDefinitionNode } from 'graphql';
import { visit } from 'graphql/language/visitor';

import { ApolloLink } from '../core';
import { Observable } from '../../utilities';
Expand All @@ -22,6 +23,7 @@ export const createHttpLink = (linkOptions: HttpOptions = {}) => {
fetch: fetcher,
includeExtensions,
useGETForQueries,
includeUnusedVariables = false,
...requestOptions
} = linkOptions;

Expand Down Expand Up @@ -85,6 +87,29 @@ export const createHttpLink = (linkOptions: HttpOptions = {}) => {
contextConfig,
);

if (body.variables && !includeUnusedVariables) {
const unusedNames = new Set(Object.keys(body.variables));
visit(operation.query, {
Variable(node, _key, parent) {
// A variable type definition at the top level of a query is not
// enough to silence server-side errors about the variable being
// unused, so variable definitions do not count as usage.
// https://spec.graphql.org/draft/#sec-All-Variables-Used
if (parent && (parent as VariableDefinitionNode).kind !== 'VariableDefinition') {
unusedNames.delete(node.name.value);
}
},
});
if (unusedNames.size) {
// Make a shallow copy of body.variables (with keys in the same
// order) and then delete unused variables from the copy.
body.variables = { ...body.variables };
unusedNames.forEach(name => {
delete body.variables![name];
});
}
}

let controller: any;
if (!(options as any).signal) {
const { controller: _controller, signal } = createSignalIfSupported();
Expand Down
11 changes: 11 additions & 0 deletions src/link/http/selectHttpOptionsAndBody.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,17 @@ export interface HttpOptions {
* to POST).
*/
useGETForQueries?: boolean;

/**
* If set to true, the default behavior of stripping unused variables
* from the request will be disabled.
*
* Unused variables are likely to trigger server-side validation errors,
* per https://spec.graphql.org/draft/#sec-All-Variables-Used, but this
* includeUnusedVariables option can be useful if your server deviates
* from the GraphQL specification by not strictly enforcing that rule.
*/
includeUnusedVariables?: boolean;
}

export interface HttpQueryOptions {
Expand Down