-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathgraphql-client.ts
62 lines (51 loc) · 1.8 KB
/
graphql-client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import type { DocumentNode } from 'graphql';
import { print } from 'graphql';
const cache = new Map<string, any>();
/**
* A minimal GraphQL client that sends a query to the Shopify API.
* @param query - The GraphQL query as a DocumentNode
* @param variables - Optional variables for the GraphQL query
* @returns The response from the Shopify API
*/
export const query = async (
query: DocumentNode,
variables = {},
maxRetries = 3
) => {
const serializedQuery = print(query);
const cacheKey = JSON.stringify({ query: serializedQuery, variables });
// Cache only collection, product, and search queries
const shouldCache = /query Collection|query Product|query Search/i.test(serializedQuery);
// Return cached response if applicable
if (shouldCache && cache.has(cacheKey)) {
return cache.get(cacheKey);
}
// Sends a fetch request to the Shopify API
const fetchRequest = async (retryCount = 0): Promise<any> => {
try {
const response = await $fetch('/api/shopify', {
method: 'POST',
body: { query: serializedQuery, variables }
});
// Cache response only if applicable
if (shouldCache) {
cache.set(cacheKey, response);
setTimeout(() => cache.delete(cacheKey), 5 * 60 * 1000); // 5 minutes
}
return response;
} catch (error: any) {
const count = retryCount + 1;
if (retryCount < maxRetries) {
console.warn(`Retrying Storefront API fetch request (${count}/${maxRetries})`);
await new Promise((resolve) => setTimeout(resolve, 1000));
return fetchRequest(count);
}
throw createError({
statusCode: 500,
statusMessage: `GraphQL fetch request failed after ${maxRetries} attempts.`,
data: { error: error.message }
});
}
};
return fetchRequest();
};