import { Blog } from '@/payload-types' import { PaginatedDocs } from 'payload' import { stringify } from 'qs-esm' /** * Fetches blog posts based on given criteria. * * @param {boolean} displayOnFrontpage - Indicates whether to display posts on the front page. * @returns {Promise | 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 | undefined> => { 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: [ { or: [ { "configuration.displayFromDate": { equals: null } }, { "configuration.displayFromDate": { less_than_equal: today.toISOString(), } } ] }, { or: [ { "configuration.displayTillDate": { equals: null } }, { "configuration.displayTillDate": { greater_than_equal: today.toISOString(), } } ] } ], }, limit: 18 }; if(displayOnFrontpage) { query.where.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(); }