Skip to content

Commit

Permalink
docs(response-cache): mention onTtl in README (#2394)
Browse files Browse the repository at this point in the history
* docs(response-cache): mention `onTtl` in README

* Avoid WeakMap
  • Loading branch information
ardatan authored Jan 27, 2025
1 parent 7882ffb commit 659ef95
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions packages/plugins/response-cache/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,59 @@ const getEnveloped = envelop({
})
```

### Manipulate the calculated TTL

If you have a some kind of custom logic, that should be used to calculate the TTL for a specific
reason. The following example tracks the `Cache-Control` header from a remote server and uses it to
calculate the TTL.

```ts
const getEnveloped = envelop({
parse,
validate,
execute,
subscribe,
plugins: [
useSchema(
makeExecutableSchema({
typeDefs: /* GraphQL */ `
type Query {
dataFromRemote: String
}
`,
resolvers: {
Query: {
dataFromRemote: async (_, __, context) => {
const res = await fetch('https://api.example.com/data')
const cacheControlHeader = res.headers.get('Cache-Control')
if (cacheControlHeader) {
const maxAgeInSeconds = cacheControlHeader.match(/max-age=(\d+)/)
if (maxAgeInSeconds) {
const ttl = parseInt(maxAgeInSeconds[1]) * 1000
if (context.ttl == null || ttl < context.ttl) {
context.ttl = ttl
}
}
}
return res.text()
}
}
}
})
),
useResponseCache({
session: () => null,
onTtl({ ttl, context }) {
if (context.ttl != null && context.ttl < ttl) {
return context.ttl
}
return ttl
}
})
]
})
```

### Expose cache metadata via extensions

For debugging or monitoring it might be useful to know whether a response got served from the cache
Expand Down

0 comments on commit 659ef95

Please sign in to comment.