45 lines
1.3 KiB
JavaScript
45 lines
1.3 KiB
JavaScript
import * as prismic from '@prismicio/client'
|
|
|
|
// === Cached API of any pris method === //
|
|
const cache = {}
|
|
export const cacheResult = (method, ...args) => {
|
|
const key = method + JSON.stringify(args || [])
|
|
|
|
// If not in cache,
|
|
// fetch and store
|
|
if (!cache[key]) {
|
|
cache[key] = () => {
|
|
const client = prismic.createClient('swang')
|
|
return client[method](...args).catch((err) => {
|
|
console.log(`Error getting Prismic result ${key}:`, err)
|
|
throw err
|
|
})
|
|
}
|
|
}
|
|
|
|
return { key, execute: cache[key] }
|
|
}
|
|
|
|
// Get single doc
|
|
export const usePrisSingle = (type, options = {}) => {
|
|
const { key, execute } = cacheResult('getSingle', type, options)
|
|
return useAsyncData(key, execute, { deep: false })
|
|
}
|
|
|
|
// Get settings (assumed single doc)
|
|
export const usePrisSettings = () => {
|
|
return usePrisSingle('settings')
|
|
}
|
|
|
|
// Get all docs of a certain type
|
|
export const usePrisType = (type, options = {}) => {
|
|
const { key, execute } = cacheResult('getAllByType', type, options)
|
|
return useAsyncData(key, execute, { deep: false })
|
|
}
|
|
|
|
// Get doc by UID (and type)
|
|
export const usePrisUid = (uid, type = 'page', options = {}) => {
|
|
const { key, execute } = cacheResult('getByUID', type, uid, options)
|
|
return useAsyncData(key, execute, { deep: false })
|
|
}
|