feat: Local API instead of fetch

This commit is contained in:
Benno Tielen 2026-03-11 11:29:16 +01:00
parent d5eca3f876
commit 267e3f9e05
30 changed files with 473 additions and 862 deletions

2
package-lock.json generated
View file

@ -11,7 +11,7 @@
"dependencies": {
"@nyariv/sandboxjs": "0.8.28",
"@payloadcms/db-postgres": "^3.74.0",
"@payloadcms/live-preview-react": "^3.79.0",
"@payloadcms/live-preview-react": "^3.74.0",
"@payloadcms/next": "^3.74.0",
"@payloadcms/richtext-lexical": "^3.74.0",
"@payloadcms/storage-gcs": "^3.74.0",

View file

@ -20,7 +20,7 @@
"dependencies": {
"@nyariv/sandboxjs": "0.8.28",
"@payloadcms/db-postgres": "^3.74.0",
"@payloadcms/live-preview-react": "^3.79.0",
"@payloadcms/live-preview-react": "^3.74.0",
"@payloadcms/next": "^3.74.0",
"@payloadcms/richtext-lexical": "^3.74.0",
"@payloadcms/storage-gcs": "^3.74.0",
@ -31,7 +31,6 @@
"moment": "^2.30.1",
"next": "15.4.11",
"payload": "^3.74.0",
"qs-esm": "^7.0.3",
"react": "19.2.4",
"react-dom": "19.2.4",
"resend": "^6.9.1",

View file

@ -1,40 +0,0 @@
'use client'
import { useEffect, useState } from 'react'
import moment from 'moment'
import Day from '@/admin/components/calendar/Day'
const Calendar = () => {
const weekNr = moment().isoWeek();
const [week, setWeek] = useState(weekNr.toString())
const [days, setDays] = useState<string[]>([])
// on week change => sey days
useEffect(() => {
const date = moment().isoWeek(Number(week));
const newDays = [];
for(let i=0; i<7; i++) {
let day = date.weekday(i).toISOString();
newDays.push(day)
}
setDays(newDays)
}, [week, setDays])
return (
<div>
<div>
<select value={week} onChange={e => setWeek(e.currentTarget.value)}>
{[...Array(51).keys()].map(i => <option key={i} value={i.toString()}>Woche {i}</option>)}
</select>
</div>
{days.map(day => <Day key={day} date={day} mass={[]} />)}
</div>
)
}
export default Calendar

View file

@ -1,22 +0,0 @@
import { useSyncExternalStore } from 'react'
import { churchStore } from '@/admin/components/calendar/ChurchSelect/churchStore'
type ChurchSelectProps = {
value: string,
className?: string,
onChange: (value: string) => void,
}
export const ChurchSelect = ({value, onChange, className}: ChurchSelectProps) => {
const churches = useSyncExternalStore(churchStore.subscribe, churchStore.getSnapshot)
return (
<select
className={className}
value={value}
onChange={e => onChange(e.target.value)}
>
{churches.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
</select>
)
}

View file

@ -1,42 +0,0 @@
import { fetchChurches } from '@/fetch/churches'
type Church = {
id: string,
name: string
}
let churches: Church[] = [];
const listeners = new Set<() => void>();
/**
* ChurchStore to use with Reacts `useSyncExternalStore`
*/
export const churchStore = {
// fetch all churches from API
async init() {
const data = await fetchChurches();
if (data) {
churches = data.docs.map(c => {
return { id: c.id, name: c.name }
});
emitChange()
}
},
subscribe: (listener: () => void) => {
listeners.add(listener);
return () => listeners.delete(listener);
},
getSnapshot() {
return churches;
}
}
function emitChange() {
for (let listener of listeners) {
listener();
}
}
await churchStore.init();

View file

@ -1,36 +0,0 @@
import { liturgicalDayName } from '@/hooks/liturgicalDayName'
import styles from "./styles.module.scss"
import MassForm from '@/admin/components/calendar/MassForm'
type DayProps = {
date: string,
mass: Mass[]
}
type Mass = {
id: string,
}
export const Day = ({date}: DayProps) => {
const dayName = liturgicalDayName(date)
const dateObj = new Date(date);
return (
<div className={styles.container}>
<div className={styles.day}>
<strong>{dateObj.toLocaleDateString("de-De", {weekday: "long"})}</strong> <br/>
{dayName}
</div>
<div className={styles.date}>
{date.substring(8, 10)}
</div>
<div>
<MassForm />
</div>
</div>
)
}
export default Day

View file

@ -1,54 +0,0 @@
import styles from "./form.module.scss"
import { ChurchSelect } from '@/admin/components/calendar/ChurchSelect/ChurchSelect'
const MassForm = () => {
return (
<div className={styles.container}>
<div className={styles.time}>
<div className={styles.formRow}>
<select name="time" className={styles.select}>
<option>10:00 Uhr</option>
<option>20:00 Uhr</option>
</select>
</div>
<div>
<ChurchSelect
className={styles.select}
value={"23"}
onChange={() => console.log("chage")}
/>
</div>
</div>
<div>
<div className={styles.formRow}>
<input type="radio" id="heilige_messe" name="massType" value="Heilige Messe" required />
<label htmlFor="heilige_messe">Heilige Messe</label>
<input type="radio" id="wort_gottes_feier" name="massType" value="Wort-Gottes-Feier" required />
<label htmlFor="wort_gottes_feier">Wort-Gottes-Feier</label>
<input type="radio" id="familienmesse" name="massType" value="Familienmesse" required />
<label htmlFor="familienmesse">Familienmesse</label>
</div>
<div className={styles.formRow}>
<input type="text" id="title" name="title" placeholder={"Titel"} className={styles.input} required />
</div>
<div className={styles.formRow}>
<input type="text" id="celebrant" name="celebrant" placeholder={"Zelebrant"} className={styles.input}/>
</div>
<div className={styles.formRow}>
<textarea id="description" name="description" placeholder={"Hinweise"} className={styles.input} rows={4}></textarea>
</div>
</div>
<div>
<button>Entfernen</button>
</div>
</div>
)
}
export default MassForm

View file

@ -1,30 +0,0 @@
.container {
display: flex;
}
.time {
width: 130px;
text-align: center;
}
.formRow {
margin-bottom: 5px;
}
.input {
font-size: 12px;
padding: 3px;
width: 350px;
border: 1px solid #ababab;
border-radius: 4px;
}
.select {
font-size: 12px;
padding: 3px;
border: 1px solid #ababab;
border-radius: 4px;
width: 100px;
background-color: #ffffff;
font-family: inherit;
}

View file

@ -1,13 +0,0 @@
.container {
display: flex;
margin-bottom: 20px;
}
.day {
width: 300px;
}
.date {
font-size: 18px;
font-weight: bold;
}

View file

@ -1,40 +0,0 @@
import { Gutter } from '@payloadcms/ui'
import { DefaultTemplate } from '@payloadcms/next/templates'
import { AdminViewProps } from 'payload'
import Calendar from '@/admin/components/calendar/Calendar'
export default function TestPage({
initPageResult,
params,
searchParams,
}: AdminViewProps) {
const {
req: {
user
}
} = initPageResult
if (!user) {
return <p>You must be logged in to view this page.</p>
}
return (
<DefaultTemplate
i18n={initPageResult.req.i18n}
locale={initPageResult.locale}
params={params}
payload={initPageResult.req.payload}
permissions={initPageResult.permissions}
searchParams={searchParams}
user={initPageResult.req.user || undefined}
visibleEntities={initPageResult.visibleEntities}
>
<Gutter>
<h1>Gottesdiensten</h1>
<p>This view uses the Default Template.</p>
<Calendar />
</Gutter>
</DefaultTemplate>
)
}

View file

@ -1,19 +1,19 @@
import { notFound } from 'next/navigation'
import { Worship as WorshipType } from '@/payload-types'
import { Worship } from '@/pageComponents/Worship/Worship'
import { isAuthenticated } from '@/utils/auth'
import { AdminMenu } from '@/components/AdminMenu/AdminMenu'
import { fetchWorshipById } from '@/fetch/worship'
export default async function WorshipPage({ params }: { params: Promise<{id: string}>}) {
const id = (await params).id;
const res = await fetch(`http://localhost:3000/api/worship/${id}`);
if (!res.ok) {
const worship = await fetchWorshipById(id)
if (!worship) {
notFound()
}
const authenticated = await isAuthenticated();
const worship = await res.json() as WorshipType;
const authenticated = await isAuthenticated();
return (
<>
@ -27,4 +27,4 @@ export default async function WorshipPage({ params }: { params: Promise<{id: str
/>
</>
)
}
}

View file

@ -1,43 +1,20 @@
import { notFound } from 'next/navigation'
import { Event } from '@/payload-types'
import { EventPage } from '@/pageComponents/Event/Event'
import { stringify } from 'qs-esm'
import { getPhoto } from '@/utils/dto/gallery'
import { cookies } from 'next/headers'
import { isAuthenticated } from '@/utils/auth'
import { fetchEventById } from '@/fetch/events'
export default async function Page({ params }: { params: Promise<{id: string}>}) {
const id = (await params).id;
const stringifiedQuery = stringify(
{
select: {
title: true,
date: true,
createdAt: true,
cancelled: true,
isRecurring: true,
location: true,
description: true,
shortDescription: true,
contact: true,
flyer: true,
photo: true,
group: true,
rsvpLink: true
},
},
{ addQueryPrefix: true },
)
const res = await fetch(`http://localhost:3000/api/event/${id}${stringifiedQuery}`);
const event = await fetchEventById(id)
if (!res.ok) {
if (!event) {
notFound()
}
const authenticated = await isAuthenticated();
const event = await res.json() as Event;
const group = Array.isArray(event.group) && event.group.length > 0 && typeof event.group[0] == "object" ? event.group[0].slug : undefined;
const photo = getPhoto("tablet", event.photo);
@ -60,4 +37,4 @@ export default async function Page({ params }: { params: Promise<{id: string}>})
isAuthenticated={authenticated}
/>
)
}
}

View file

@ -1,6 +1,6 @@
import { CollectionConfig } from 'payload'
import { stringify } from 'qs-esm'
import { Event, Group, User } from '@/payload-types'
import { Group, User } from '@/payload-types'
import { fetchEventById } from '@/fetch/events'
export const Events: CollectionConfig = {
slug: 'event',
@ -198,7 +198,7 @@ export const Events: CollectionConfig = {
return false
}
const event = await fetchEvent(id)
const event = await fetchEventById(id)
if (hasGroup(user, event)) {
return true
}
@ -235,20 +235,3 @@ const hasGroup = (user: null | User , data: Partial<any> | undefined) => {
})
}
/**
* Fetch event
* @param id
*/
const fetchEvent = async (id: string): Promise<undefined|Event> => {
const stringifiedQuery = stringify(
{
select: {
group: true,
},
},
{ addQueryPrefix: true },
)
const res = await fetch(`http://localhost:3000/api/event/${id}${stringifiedQuery}`);
if (!res.ok) return undefined
return res.json()
}

View file

@ -1,87 +1,75 @@
import { stringify } from 'qs-esm'
import { getPayload } from 'payload'
import config from '@/payload.config'
import { Announcement } from '@/payload-types'
import { PaginatedDocs } from 'payload'
/**
* Fetch last announcement for a parish
*/
export const fetchLastAnnouncement = async (parishId: string): Promise<Announcement | undefined> => {
const date = new Date();
export const fetchLastAnnouncement = async (
parishId: string,
): Promise<Announcement | undefined> => {
const date = new Date()
date.setDate(date.getDate() - 14)
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(23,59,59,59);
const tomorrow = new Date()
tomorrow.setDate(tomorrow.getDate() + 1)
tomorrow.setHours(23, 59, 59, 59)
const query: any = {
and: [
{
parish: {
equals: parishId
}
},
{
date: {
greater_than_equal: date.toISOString(),
}
},
{
date: {
less_than_equal: tomorrow.toISOString()
}
}
]
}
const stringifiedQuery = stringify(
{
sort: "-date",
where: query,
limit: 1,
const payload = await getPayload({ config })
const result = await payload.find({
collection: 'announcement',
sort: '-date',
where: {
and: [
{
parish: {
equals: parishId,
},
},
{
date: {
greater_than_equal: date.toISOString(),
},
},
{
date: {
less_than_equal: tomorrow.toISOString(),
},
},
],
},
{ addQueryPrefix: true },
)
const response = await fetch(`http://localhost:3000/api/announcement${stringifiedQuery}`)
if (!response.ok) return undefined
const announcements = await response.json() as PaginatedDocs<Announcement>
return announcements.docs[0]
limit: 1,
})
return result.docs[0]
}
/**
* Fetch the last few announcements
*/
export const fetchLastAnnouncements = async (): Promise<PaginatedDocs<Announcement> | undefined> => {
const date = new Date();
export const fetchLastAnnouncements = async () => {
const date = new Date()
date.setDate(date.getDate() - 14)
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(23,59,59,59);
const tomorrow = new Date()
tomorrow.setDate(tomorrow.getDate() + 1)
tomorrow.setHours(23, 59, 59, 59)
const query: any = {
and: [
{
date: {
greater_than_equal: date.toISOString(),
}
},
{
date: {
less_than_equal: tomorrow.toISOString()
}
}
]
}
const stringifiedQuery = stringify(
{
sort: "-date",
where: query,
limit: 3,
const payload = await getPayload({ config })
return payload.find({
collection: 'announcement',
sort: '-date',
where: {
and: [
{
date: {
greater_than_equal: date.toISOString(),
},
},
{
date: {
less_than_equal: tomorrow.toISOString(),
},
},
],
},
{ addQueryPrefix: true },
)
const response = await fetch(`http://localhost:3000/api/announcement${stringifiedQuery}`)
if (!response.ok) return undefined
return await response.json() as PaginatedDocs<Announcement>
}
limit: 3,
})
}

View file

@ -1,73 +1,67 @@
import { Blog } from '@/payload-types'
import { PaginatedDocs } from 'payload'
import { stringify } from 'qs-esm'
import { getPayload } from 'payload'
import config from '@/payload.config'
/**
* Fetches blog posts based on given criteria.
*
* @param {boolean} displayOnFrontpage - Indicates whether to display posts on the front page.
* @returns {Promise<PaginatedDocs<Blog> | undefined>} - A Promise that resolves to the paginated list of blog posts, or undefined if an error occurs.
*/
export const fetchBlogPosts = async (displayOnFrontpage: boolean): Promise<PaginatedDocs<Blog> | undefined> => {
const today = new Date();
today.setHours(23, 59);
export const fetchBlogPosts = async (displayOnFrontpage: boolean) => {
const today = new Date()
today.setHours(23, 59)
const query: any =
{
sort: "-date",
select: {
title: true,
date: true,
photo: true,
content: displayOnFrontpage ? undefined : true, // hack to fetch content only for the `/blog` page
},
where: {
and: [
const query: any = {
and: [
{
or: [
{
or: [
{
"configuration.displayFromDate": {
equals: null
}
},
{
"configuration.displayFromDate": {
less_than_equal: today.toISOString(),
}
}
]
'configuration.displayFromDate': {
equals: null,
},
},
{
or: [
{
"configuration.displayTillDate": {
equals: null
}
},
{
"configuration.displayTillDate": {
greater_than_equal: today.toISOString(),
}
}
]
}
'configuration.displayFromDate': {
less_than_equal: today.toISOString(),
},
},
],
},
limit: 18
};
{
or: [
{
'configuration.displayTillDate': {
equals: null,
},
},
{
'configuration.displayTillDate': {
greater_than_equal: today.toISOString(),
},
},
],
},
],
}
if(displayOnFrontpage) {
query.where.and.push({
"configuration.showOnFrontpage": {
equals: true
if (displayOnFrontpage) {
query.and.push({
'configuration.showOnFrontpage': {
equals: true,
},
})
}
const stringifiedQuery = stringify(query, {addQueryPrefix: true})
const resp = await fetch(`http://localhost:3000/api/blog${stringifiedQuery}`);
if (!resp.ok) return undefined;
return resp.json();
}
const payload = await getPayload({ config })
return payload.find({
collection: 'blog',
sort: '-date',
select: {
title: true,
date: true,
photo: true,
content: displayOnFrontpage ? undefined : true,
},
where: query,
limit: 18,
})
}

View file

@ -1,89 +1,75 @@
import { stringify } from 'qs-esm'
import { PaginatedDocs } from 'payload'
import { getPayload } from 'payload'
import config from '@/payload.config'
import { Calendar } from '@/payload-types'
/**
* Fetch last calendar for a parish
*/
export const fetchLastCalendar = async (parishId: string): Promise<Calendar | undefined> => {
const date = new Date();
date.setDate(date.getDate() - 14);
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(23,59,59,59);
export const fetchLastCalendar = async (
parishId: string,
): Promise<Calendar | undefined> => {
const date = new Date()
date.setDate(date.getDate() - 14)
const tomorrow = new Date()
tomorrow.setDate(tomorrow.getDate() + 1)
tomorrow.setHours(23, 59, 59, 59)
const query: any = {
and: [
{
parish: {
equals: parishId
}
},
{
date: {
greater_than_equal: date.toISOString(),
}
},
{
date: {
less_than_equal: tomorrow.toISOString()
}
}
]
}
const stringifiedQuery = stringify(
{
sort: "-date",
where: query,
limit: 1,
const payload = await getPayload({ config })
const result = await payload.find({
collection: 'calendar',
sort: '-date',
where: {
and: [
{
parish: {
equals: parishId,
},
},
{
date: {
greater_than_equal: date.toISOString(),
},
},
{
date: {
less_than_equal: tomorrow.toISOString(),
},
},
],
},
{ addQueryPrefix: true },
)
const response = await fetch(`http://localhost:3000/api/calendar${stringifiedQuery}`)
if (!response.ok) return undefined
const announcements = await response.json() as PaginatedDocs<Calendar>
return announcements.docs[0]
limit: 1,
})
return result.docs[0]
}
/**
* Fetch last calendars
*/
export const fetchLastCalendars = async (): Promise<PaginatedDocs<Calendar> | undefined> => {
const date = new Date();
date.setDate(date.getDate() - 14);
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(23,59,59,59);
export const fetchLastCalendars = async () => {
const date = new Date()
date.setDate(date.getDate() - 14)
const tomorrow = new Date()
tomorrow.setDate(tomorrow.getDate() + 1)
tomorrow.setHours(23, 59, 59, 59)
const query: any = {
and: [
{
date: {
greater_than_equal: date.toISOString(),
}
},
{
date: {
less_than_equal: tomorrow.toISOString()
}
}
]
}
const stringifiedQuery = stringify(
{
sort: "-date",
where: query,
limit: 3,
const payload = await getPayload({ config })
return payload.find({
collection: 'calendar',
sort: '-date',
where: {
and: [
{
date: {
greater_than_equal: date.toISOString(),
},
},
{
date: {
less_than_equal: tomorrow.toISOString(),
},
},
],
},
{ addQueryPrefix: true },
)
const response = await fetch(`http://localhost:3000/api/calendar${stringifiedQuery}`)
if (!response.ok) return undefined
return await response.json() as PaginatedDocs<Calendar>
}
limit: 3,
})
}

View file

@ -1,17 +0,0 @@
import { Church } from '@/payload-types'
import { PaginatedDocs } from 'payload'
import { stringify } from 'qs-esm'
export const fetchChurches = async (): Promise<PaginatedDocs<Church> | undefined> => {
const stringifiedQuery = stringify(
{
sort: "name",
limit: 50
},
{ addQueryPrefix: true },
)
const resp = await fetch(`http://localhost:3000/api/church`);
if (!resp.ok) return undefined;
return resp.json();
}

View file

@ -1,27 +1,19 @@
import { PaginatedDocs } from 'payload'
import { Classified } from '@/payload-types'
import { stringify } from 'qs-esm'
import { getPayload } from 'payload'
import config from '@/payload.config'
export const fetchClassifieds = async (): Promise<PaginatedDocs<Classified> | undefined> => {
const date = new Date();
date.setHours(0, 0, 0, 0);
export const fetchClassifieds = async () => {
const date = new Date()
date.setHours(0, 0, 0, 0)
const query = {
until: {
greater_than_equal: date.toISOString(),
}
}
const stringifiedQuery = stringify(
{
sort: "date",
where: query,
limit: 50
const payload = await getPayload({ config })
return payload.find({
collection: 'classifieds',
sort: 'date',
where: {
until: {
greater_than_equal: date.toISOString(),
},
},
{ addQueryPrefix: true },
)
const response = await fetch(`http://localhost:3000/api/classifieds${stringifiedQuery}`)
if (!response.ok) return undefined
return response.json()
limit: 50,
})
}

View file

@ -1,13 +1,13 @@
import { unstable_cache } from 'next/cache'
import { getPayload } from 'payload'
import config from '@/payload.config'
import { Menu } from '@/payload-types'
export const fetchMenu = async (): Promise<Menu> => {
const rep = await fetch(
"http://localhost:3000/api/globals/menu",
{ next: { tags: ['menu'] } } // cache fetch result
);
if (!rep.ok) {
throw new Error("Could not fetch menu")
}
return await rep.json()
}
export const fetchMenu = unstable_cache(
async (): Promise<Menu> => {
const payload = await getPayload({ config })
return payload.findGlobal({ slug: 'menu' })
},
['menu'],
{ tags: ['menu'] },
)

View file

@ -1,21 +1,17 @@
import { getPayload } from 'payload'
import config from '@/payload.config'
import { DonationForm } from '@/payload-types'
export async function fetchDonationForm(id: string): Promise<DonationForm | undefined> {
// const query = {
// id: {
// equals: id,
// },
// }
//
// const stringifiedQuery = stringify(
// {
// where: query,
// },
// { addQueryPrefix: true },
// )
const res = await fetch(`http://localhost:3000/api/donation-form/${id}`);
if (!res.ok) return undefined
const response = await res.json() as DonationForm;
return response
}
export async function fetchDonationForm(
id: string,
): Promise<DonationForm | undefined> {
try {
const payload = await getPayload({ config })
return await payload.findByID({
collection: 'donation-form',
id,
})
} catch {
return undefined
}
}

View file

@ -1,25 +1,30 @@
import { stringify } from 'qs-esm'
import { PaginatedDocs } from 'payload'
import { getPayload, PaginatedDocs } from 'payload'
import config from '@/payload.config'
import { Event } from '@/payload-types'
type Args = {
parishId?: string;
groupId?: string;
limit?: number;
page?: number;
parishId?: string
groupId?: string
limit?: number
page?: number
fromDate?: Date
toDate?: Date
}
/**
* Fetch a list of events
*
*/
export async function fetchEvents(args?: Args): Promise<PaginatedDocs<Event> | undefined> {
const {parishId, groupId, limit = 30, page = 0, fromDate = new Date(), toDate} = args || {};
export async function fetchEvents(
args?: Args,
): Promise<PaginatedDocs<Event>> {
const {
parishId,
groupId,
limit = 30,
page = 0,
fromDate = new Date(),
toDate,
} = args || {}
const query: any = {
and: [
@ -27,7 +32,7 @@ export async function fetchEvents(args?: Args): Promise<PaginatedDocs<Event> | u
date: {
greater_than_equal: fromDate.toISOString(),
},
}
},
],
}
@ -35,45 +40,53 @@ export async function fetchEvents(args?: Args): Promise<PaginatedDocs<Event> | u
query.and.push({
date: {
less_than: toDate.toISOString(),
}
},
})
}
if (parishId) {
query.and.push({
"parish": {
equals: parishId
parish: {
equals: parishId,
},
})
}
if (groupId) {
query.and.push({
"group": {
equals: groupId
}
group: {
equals: groupId,
},
})
}
const stringifiedQuery = stringify(
{
sort: "date",
where: query,
select: {
location: true,
date: true,
title: true,
cancelled: true
},
depth: 1,
limit,
page
const payload = await getPayload({ config })
return payload.find({
collection: 'event',
sort: 'date',
where: query,
select: {
location: true,
date: true,
title: true,
cancelled: true,
},
{ addQueryPrefix: true },
)
const response = await fetch(`http://localhost:3000/api/event${stringifiedQuery}`)
if (!response.ok) return undefined
return response.json()
depth: 1,
limit,
page,
}) as Promise<PaginatedDocs<Event>>
}
/**
* Fetch a single event by ID
*/
export async function fetchEventById(
id: string,
): Promise<Event | undefined> {
try {
const payload = await getPayload({ config })
return await payload.findByID({ collection: 'event', id })
} catch {
return undefined
}
}

View file

@ -1,13 +1,13 @@
import { unstable_cache } from 'next/cache'
import { getPayload } from 'payload'
import config from '@/payload.config'
import { Footer } from '@/payload-types'
export async function fetchFooter(): Promise<Footer> {
const res = await fetch('http://localhost:3000/api/globals/footer', {
next: { tags: ['footer'] },
})
if (!res.ok) {
throw new Error('Could not fetch footer')
}
return res.json()
}
export const fetchFooter = unstable_cache(
async (): Promise<Footer> => {
const payload = await getPayload({ config })
return payload.findGlobal({ slug: 'footer' })
},
['footer'],
{ tags: ['footer'] },
)

View file

@ -1,22 +1,14 @@
import { stringify } from 'qs-esm'
import { PaginatedDocs } from 'payload'
import { Group } from '@/payload-types'
import { getPayload } from 'payload'
import config from '@/payload.config'
export async function fetchGroup(slug: string): Promise<PaginatedDocs<Group> | undefined> {
const query = {
slug: {
equals: slug,
export async function fetchGroup(slug: string) {
const payload = await getPayload({ config })
return payload.find({
collection: 'group',
where: {
slug: {
equals: slug,
},
},
}
const stringifiedQuery = stringify(
{
where: query,
},
{ addQueryPrefix: true },
)
const res = await fetch(`http://localhost:3000/api/group${stringifiedQuery}`)
if (!res.ok) return undefined
return res.json()
}
})
}

View file

@ -1,64 +1,52 @@
import { stringify } from 'qs-esm'
import { PaginatedDocs } from 'payload'
import { Highlight } from '@/payload-types'
import { getPayload } from 'payload'
import config from '@/payload.config'
export const fetchHighlights = async (): Promise<PaginatedDocs<Highlight> | undefined> => {
const date = new Date();
date.setHours(0, 0, 0, 0);
export const fetchHighlights = async () => {
const date = new Date()
date.setHours(0, 0, 0, 0)
const query: any = {
and: [
{
from: {
less_than_equal: date.toISOString(),
const payload = await getPayload({ config })
return payload.find({
collection: 'highlight',
sort: 'date',
where: {
and: [
{
from: {
less_than_equal: date.toISOString(),
},
until: {
greater_than_equal: date.toISOString(),
},
},
until: {
greater_than_equal: date.toISOString(),
}
}
],
}
const stringifiedQuery = stringify(
{
sort: "date",
where: query,
limit: 3
],
},
{ addQueryPrefix: true },
)
const response = await fetch(`http://localhost:3000/api/highlight${stringifiedQuery}`)
if (!response.ok) return undefined
return response.json()
limit: 3,
})
}
export const fetchHighlightsBetweenDates = async (from: Date, until: Date): Promise<PaginatedDocs<Highlight> | undefined> => {
const query: any = {
and: [
{
date: {
greater_than_equal: from.toISOString(),
}
},
{
date: {
less_than: until.toISOString(),
}
}
],
}
const stringifiedQuery = stringify(
{
sort: "date",
where: query,
limit: 5
export const fetchHighlightsBetweenDates = async (
from: Date,
until: Date,
) => {
const payload = await getPayload({ config })
return payload.find({
collection: 'highlight',
sort: 'date',
where: {
and: [
{
date: {
greater_than_equal: from.toISOString(),
},
},
{
date: {
less_than: until.toISOString(),
},
},
],
},
{ addQueryPrefix: true },
)
const response = await fetch(`http://localhost:3000/api/highlight${stringifiedQuery}`)
if (!response.ok) return undefined
return response.json()
}
limit: 5,
})
}

View file

@ -1,27 +1,20 @@
import { stringify } from 'qs-esm'
import { PaginatedDocs } from 'payload'
import { getPayload } from 'payload'
import config from '@/payload.config'
import { Magazine } from '@/payload-types'
/**
* Asynchronously fetches the last magazine entry from the specified API endpoint.
* Asynchronously fetches the last magazine entry.
*
* This function sends a request to the specified API endpoint to fetch the last magazine based on the given sorting criteria.
*
* @returns {Promise<Magazine | undefined>} A Promise that resolves to the last fetched magazine entry if successful, or undefined if an error occurs.
* @returns {Promise<Magazine | undefined>} The last magazine entry if successful, or undefined.
*/
export const fetchLastMagazine = async (): Promise<Magazine | undefined> => {
const stringifiedQuery = stringify(
{
sort: "-date",
limit: 1,
},
{ addQueryPrefix: true },
)
const response = await fetch(`http://localhost:3000/api/magazine${stringifiedQuery}`)
if (!response.ok) return undefined
const announcements = await response.json() as PaginatedDocs<Magazine>
return announcements.docs[0]
}
export const fetchLastMagazine = async (): Promise<
Magazine | undefined
> => {
const payload = await getPayload({ config })
const result = await payload.find({
collection: 'magazine',
sort: '-date',
limit: 1,
})
return result.docs[0]
}

View file

@ -1,25 +1,26 @@
import { unstable_cache } from 'next/cache'
import { getPayload } from 'payload'
import config from '@/payload.config'
import { Page } from '@/payload-types'
import { stringify } from 'qs-esm'
export async function fetchPageBySlug(
slug: string,
): Promise<Page | undefined> {
const query = stringify(
{
where: {
slug: {
equals: slug,
return unstable_cache(
async () => {
const payload = await getPayload({ config })
const data = await payload.find({
collection: 'pages',
where: {
slug: {
equals: slug,
},
},
},
limit: 1,
limit: 1,
})
return data.docs?.[0] ?? undefined
},
{ addQueryPrefix: true },
)
const res = await fetch(`http://localhost:3000/api/pages${query}`, {
next: { tags: ['pages', `pages-${slug}`] },
})
if (!res.ok) return undefined
const data = await res.json()
return data.docs?.[0]
['pages', slug],
{ tags: ['pages', `pages-${slug}`] },
)()
}

View file

@ -1,22 +1,14 @@
import { stringify } from 'qs-esm'
import { PaginatedDocs } from 'payload'
import { Parish } from '@/payload-types'
import { getPayload } from 'payload'
import config from '@/payload.config'
export async function fetchParish(slug: string): Promise<PaginatedDocs<Parish> | undefined> {
const query = {
slug: {
equals: slug,
export async function fetchParish(slug: string) {
const payload = await getPayload({ config })
return payload.find({
collection: 'parish',
where: {
slug: {
equals: slug,
},
},
}
const stringifiedQuery = stringify(
{
where: query,
},
{ addQueryPrefix: true },
)
const res = await fetch(`http://localhost:3000/api/parish${stringifiedQuery}`)
if (!res.ok) return undefined
return res.json()
}
})
}

View file

@ -1,4 +1,5 @@
import { stringify } from 'qs-esm'
import { getPayload } from 'payload'
import config from '@/payload.config'
import { PopePrayerIntention } from '@/payload-types'
/**
@ -7,30 +8,26 @@ import { PopePrayerIntention } from '@/payload-types'
* @param year
* @param month - in the form of '01' for january, '02' for february ...
*/
export const fetchPopePrayerIntentions = async (year: number, month: string): Promise<PopePrayerIntention | undefined> => {
const query: any = {
and: [
{
month: {
equals: month,
export const fetchPopePrayerIntentions = async (
year: number,
month: string,
): Promise<PopePrayerIntention | undefined> => {
const payload = await getPayload({ config })
const result = await payload.find({
collection: 'popePrayerIntentions',
where: {
and: [
{
month: {
equals: month,
},
year: {
equals: year,
},
},
year: {
equals: year
}
}
],
}
const stringifiedQuery = stringify(
{
where: query,
limit: 1
],
},
{ addQueryPrefix: true },
)
const response = await fetch(`http://localhost:3000/api/popePrayerIntentions${stringifiedQuery}`)
if (!response.ok) return undefined
let data = await response.json()
return data.docs[0]
}
limit: 1,
})
return result.docs[0]
}

View file

@ -1,11 +1,16 @@
import { Prayer } from '@/payload-types'
import { unstable_cache } from 'next/cache'
import { getPayload } from 'payload'
import config from '@/payload.config'
export async function fetchPrayers(): Promise<string[]> {
const res = await fetch(
'http://localhost:3000/api/prayers?limit=0',
{ next: { tags: ['prayers'] } },
)
if (!res.ok) return []
const data = await res.json()
return (data.docs as Prayer[]).map((p) => p.text)
}
export const fetchPrayers = unstable_cache(
async (): Promise<string[]> => {
const payload = await getPayload({ config })
const data = await payload.find({
collection: 'prayers',
limit: 0,
})
return data.docs.map((p) => p.text)
},
['prayers'],
{ tags: ['prayers'] },
)

View file

@ -1,67 +1,76 @@
import { stringify } from 'qs-esm'
import { PaginatedDocs } from 'payload'
import { getPayload, PaginatedDocs } from 'payload'
import config from '@/payload.config'
import { Worship } from '@/payload-types'
type FetchWorshipArgs = {
fromDate?: Date,
tillDate?: Date,
fromDate?: Date
tillDate?: Date
locations?: string[]
}
export const fetchWorship = async (args?: FetchWorshipArgs): Promise<PaginatedDocs<Worship> | undefined> => {
export const fetchWorship = async (
args?: FetchWorshipArgs,
): Promise<PaginatedDocs<Worship>> => {
const { fromDate, tillDate, locations } = args || {}
const {fromDate, tillDate, locations} = args || {}
let date = fromDate;
let date = fromDate
if (!date) {
date = new Date();
date.setHours(0, 0, 0, 0);
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()
}
less_than: tillDate.toISOString(),
},
})
}
if (locations ) {
if (locations) {
query.and.push({
location: {
in: locations
}
in: locations,
},
})
}
const stringifiedQuery = stringify(
{
sort: "date",
where: query,
select: {
type: true,
date: true,
cancelled: true,
location: true,
title: true,
},
limit: 15
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,
},
{ addQueryPrefix: true },
)
limit: 15,
}) as Promise<PaginatedDocs<Worship>>
}
const response = await fetch(`http://localhost:3000/api/worship${stringifiedQuery}`)
if (!response.ok) return undefined
return response.json()
}
/**
* 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
}
}