Skip to content

Commit

Permalink
docs: refactor custom-caching example
Browse files Browse the repository at this point in the history
  • Loading branch information
angeloashmore committed May 21, 2021
1 parent c4b2e2f commit 9dd2daa
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 32 deletions.
37 changes: 35 additions & 2 deletions examples/custom-caching/index.js
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.
30 changes: 0 additions & 30 deletions examples/custom-caching/prismic.js

This file was deleted.

0 comments on commit 9dd2daa

Please sign in to comment.