Skip to content
This repository has been archived by the owner on Apr 11, 2024. It is now read-only.

Handle data objects with variables in GraphQL Client #97

Merged
merged 2 commits into from
Feb 9, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
10 changes: 9 additions & 1 deletion src/clients/graphql/graphql_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ export class GraphqlClient {
params.extraHeaders = {[ShopifyHeader.AccessToken]: this.token, ...params.extraHeaders};
const path = `/admin/api/${Context.API_VERSION}/graphql.json`;

return this.client.post({path, type: DataType.GraphQL, ...params});
let dataType: DataType.GraphQL | DataType.JSON;

if (typeof params.data === 'object') {
dataType = DataType.JSON;
} else {
thecodepixi marked this conversation as resolved.
Show resolved Hide resolved
dataType = DataType.GraphQL;
}

return this.client.post({path, type: dataType, ...params});
}
}
44 changes: 43 additions & 1 deletion src/clients/graphql/test/graphql_client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,53 @@ describe('GraphQL client', () => {

fetchMock.mockResponseOnce(JSON.stringify(successResponse));

await expect(client.query({extraHeaders: customHeader, data: QUERY})).resolves.toEqual(buildExpectedResponse(successResponse));
await expect(client.query({extraHeaders: customHeader, data: QUERY})).resolves.toEqual(
buildExpectedResponse(successResponse),
);

customHeader[ShopifyHeader.AccessToken] = 'bork';
assertHttpRequest('POST', DOMAIN, '/admin/api/unstable/graphql.json', customHeader, QUERY);
});

it('can handle queries with variables', async () => {
const client: GraphqlClient = new GraphqlClient(DOMAIN, 'bork');
const queryWithVariables = {
query: `query FirstTwo($first: Int) {
products(first: $first) {
edges {
node {
id
}
}
}
}`,
variables: `{
'first': 2,
}`,
};
const expectedResponse = {
data: {
products: {
edges: [
{
node: {
id: 'foo',
},
},
{
node: {
id: 'bar',
},
},
],
},
},
};

fetchMock.mockResponseOnce(JSON.stringify(expectedResponse));

await expect(client.query({data: queryWithVariables})).resolves.toEqual(buildExpectedResponse(expectedResponse));
thecodepixi marked this conversation as resolved.
Show resolved Hide resolved
});
});

function buildExpectedResponse(obj: unknown) {
Expand Down