Skip to content

Commit 659ef95

Browse files
authored
docs(response-cache): mention onTtl in README (#2394)
* docs(response-cache): mention `onTtl` in README * Avoid WeakMap
1 parent 7882ffb commit 659ef95

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

packages/plugins/response-cache/README.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -695,6 +695,59 @@ const getEnveloped = envelop({
695695
})
696696
```
697697

698+
### Manipulate the calculated TTL
699+
700+
If you have a some kind of custom logic, that should be used to calculate the TTL for a specific
701+
reason. The following example tracks the `Cache-Control` header from a remote server and uses it to
702+
calculate the TTL.
703+
704+
```ts
705+
const getEnveloped = envelop({
706+
parse,
707+
validate,
708+
execute,
709+
subscribe,
710+
plugins: [
711+
useSchema(
712+
makeExecutableSchema({
713+
typeDefs: /* GraphQL */ `
714+
type Query {
715+
dataFromRemote: String
716+
}
717+
`,
718+
resolvers: {
719+
Query: {
720+
dataFromRemote: async (_, __, context) => {
721+
const res = await fetch('https://api.example.com/data')
722+
const cacheControlHeader = res.headers.get('Cache-Control')
723+
if (cacheControlHeader) {
724+
const maxAgeInSeconds = cacheControlHeader.match(/max-age=(\d+)/)
725+
if (maxAgeInSeconds) {
726+
const ttl = parseInt(maxAgeInSeconds[1]) * 1000
727+
if (context.ttl == null || ttl < context.ttl) {
728+
context.ttl = ttl
729+
}
730+
}
731+
}
732+
return res.text()
733+
}
734+
}
735+
}
736+
})
737+
),
738+
useResponseCache({
739+
session: () => null,
740+
onTtl({ ttl, context }) {
741+
if (context.ttl != null && context.ttl < ttl) {
742+
return context.ttl
743+
}
744+
return ttl
745+
}
746+
})
747+
]
748+
})
749+
```
750+
698751
### Expose cache metadata via extensions
699752

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

0 commit comments

Comments
 (0)