church-website/src/utils/randomTestimony.ts
2024-08-22 15:49:33 +02:00

35 lines
877 B
TypeScript

import { getPayloadHMR } from '@payloadcms/next/utilities'
import configPromise from '@payload-config'
import { unstable_cache } from 'next/cache'
type Category = 'EUCHARIST'
/**
* Fetch testimonials from database
*/
const fetchTestimonies = async (type: Category) => {
const payload = await getPayloadHMR({ config: configPromise })
return await payload.find({
collection: 'testimony',
sort: 'createdAt',
where: {
category: {
equals: type,
},
},
})
}
/**
* Fetch a random cached testimony
*/
export const randomTestimony = async (type: Category) => {
const testimonials = await unstable_cache(
() => fetchTestimonies(type),
['testimony', type],
{ revalidate: 3600 },
)()
const length = testimonials.docs.length
const randomIndex = Math.floor(Math.random() * length)
return testimonials.docs[randomIndex]
}