Skip to content

Commit

Permalink
Make sure that we don't cache sub-requests that 400-500 error (#2554)
Browse files Browse the repository at this point in the history
  • Loading branch information
blittle authored Apr 15, 2024
1 parent ba57245 commit 2034e00
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/odd-melons-wash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@shopify/hydrogen': patch
---

Make sure sub-requests that are 400 or 500 HTTP errors are not cached
17 changes: 10 additions & 7 deletions packages/hydrogen/src/hooks/useShopQuery/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,6 @@ export interface UseShopQueryResponse<T> {
errors: any;
}

// Check if the response body has GraphQL errors
// https://spec.graphql.org/June2018/#sec-Response-Format
const shouldCacheResponse = (body: any) => {
return !body?.errors;
};

/**
* The `useShopQuery` hook allows you to make server-only GraphQL queries to the Storefront API. It must be a descendent of a `ShopifyProvider` component.
*/
Expand Down Expand Up @@ -77,6 +71,15 @@ export function useShopQuery<T>({

const body = query ? graphqlRequestBody(query, variables) : '';

let _response: Response;

// Check if the response body has GraphQL errors
// https://spec.graphql.org/June2018/#sec-Response-Format
// and that the response is not an error
const shouldCacheResponse = (body: any) => {
return !body?.errors && _response?.ok;
};

const {data, error} = useQuery(
[storeDomain, storefrontApiVersion, body],
async (request) => {
Expand All @@ -89,7 +92,7 @@ export function useShopQuery<T>({
storefrontId,
privateStorefrontToken,
});
const response = await fetch(url, requestInit);
const response = (_response = await fetch(url, requestInit));
const text = await response.text();

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,21 @@ describe('useShopQuery', () => {

expect(await cache.keys()).toHaveLength(0);
});

it('handles 500 errors', async () => {
mockedFetch.mockResolvedValue(new Response('{}', {status: 500}));
const component = await mountComponent();

expect(await cache.keys()).toHaveLength(0);

await component.act(async () => {
await Promise.all(waitUntilPromises);
});

expect(component).toContainReactComponent('div', {
children: '{}',
});

expect(await cache.keys()).toHaveLength(0);
});
});

0 comments on commit 2034e00

Please sign in to comment.