church-website/src/fetch/worship.ts
2026-04-09 11:12:54 +02:00

76 lines
1.4 KiB
TypeScript

import { getPayload, PaginatedDocs } from 'payload'
import config from '@/payload.config'
import { Worship } from '@/payload-types'
type FetchWorshipArgs = {
fromDate?: Date
tillDate?: Date
locations?: string[]
}
export const fetchWorship = async (
args?: FetchWorshipArgs,
): Promise<PaginatedDocs<Worship>> => {
const { fromDate, tillDate, locations } = args || {}
let date = fromDate
if (!date) {
date = new Date()
date.setHours(0, 0, 0, 0)
}
const query: any = {
and: [
{
date: {
greater_than_equal: date.toISOString(),
},
},
],
}
if (tillDate) {
query.and.push({
date: {
less_than: tillDate.toISOString(),
},
})
}
if (locations) {
query.and.push({
location: {
in: locations,
},
})
}
const payload = await getPayload({ config })
return payload.find({
collection: 'worship',
sort: 'date',
where: query,
select: {
type: true,
date: true,
cancelled: true,
location: true,
title: true,
},
limit: 100,
}) as Promise<PaginatedDocs<Worship>>
}
/**
* Fetch a single worship entry by ID
*/
export async function fetchWorshipById(
id: string,
): Promise<Worship | undefined> {
try {
const payload = await getPayload({ config })
return await payload.findByID({ collection: 'worship', id })
} catch {
return undefined
}
}