-
Notifications
You must be signed in to change notification settings - Fork 60
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
docs: refactor custom-caching example
- Loading branch information
1 parent
c4b2e2f
commit 9dd2daa
Showing
2 changed files
with
35 additions
and
32 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,38 @@ | ||
import { client } from './prismic' | ||
import * as prismic from '@prismicio/client' | ||
import QuickLRU from 'quick-lru' | ||
|
||
const endpoint = prismic.getEndpoint('my-repo') | ||
const cache = new QuickLRU({ | ||
maxAge: 10000, // 10 seconds | ||
maxSize: 1000, // 1000 entries | ||
}) | ||
|
||
export const client = prismic.createClient(endpoint, { | ||
fetch: async (url, options) => { | ||
// The cache key contains the requested URL and headers | ||
const key = JSON.stringify({ url, options }) | ||
|
||
if (cache.has(key)) { | ||
// If the cache contains a value for the key, return it | ||
return cache.get(key) | ||
} else { | ||
// Otherwise, make the network request | ||
const res = await fetch(url, options) | ||
|
||
if (res.ok) { | ||
// If the request was successful, save it to the cache | ||
cache.set(key, res) | ||
} | ||
|
||
return res | ||
} | ||
}, | ||
}) | ||
|
||
const homepage = await client.getByUID('page', 'home') | ||
console.log(homepage) | ||
// => The `page` document with a UID of `home` | ||
|
||
console.log(homepage.data) | ||
const homepageFetchedAgain = await client.getByUID('page', 'home') | ||
console.log(homepageFetchedAgain) | ||
// => This call will use the cache rather than make another network request. |
This file was deleted.
Oops, something went wrong.