Use GOT cache mechanism to cache GRAPHQL responses #2292
-
|
Is that possible to cache post requests on a GRAPHQL endpoint? Could help me with some ideas to accomplish this? I already tried to use the got cache mechanism with redis but by now, without success. Thank you very much! |
Beta Was this translation helpful? Give feedback.
Answered by
sindresorhus
Oct 11, 2025
Replies: 1 comment
-
|
By default, Got doesn't cache POST requests since they're typically not idempotent. For GraphQL queries, the simplest approach is to wrap your Got calls with a caching layer: import got from 'got';
import Keyv from 'keyv';
import KeyvRedis from '@keyv/redis';
const cache = new Keyv({
store: new KeyvRedis('redis://localhost:6379')
});
async function cachedGraphQL(url, query, variables = {}) {
const cacheKey = JSON.stringify({ query, variables });
// Check cache first
const cached = await cache.get(cacheKey);
if (cached) {
return cached;
}
// Make request if not cached
const response = await got.post(url, {
json: { query, variables }
}).json();
// Cache for 5 minutes
await cache.set(cacheKey, response, 300000);
return response;
}
// Usage
const data = await cachedGraphQL('https://api.example.com/graphql', `
query {
users {
id
name
}
}
`);This gives you full controll over what gets cached and for how long. |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
sindresorhus
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
By default, Got doesn't cache POST requests since they're typically not idempotent. For GraphQL queries, the simplest approach is to wrap your Got calls with a caching layer: