diff --git a/examples/custom-server/.env.example b/examples/custom-server/.env.example index bb16827c88..8e607e9b0b 100644 --- a/examples/custom-server/.env.example +++ b/examples/custom-server/.env.example @@ -3,4 +3,3 @@ PAYLOAD_SECRET=PAYLOAD_CUSTOM_SERVER_EXAMPLE_SECRET_KEY PAYLOAD_PUBLIC_SERVER_URL=http://localhost:3000 NEXT_PUBLIC_SERVER_URL=http://localhost:3000 PAYLOAD_SEED=true -PAYLOAD_DROP_DATABASE=true diff --git a/examples/custom-server/src/app/page.tsx b/examples/custom-server/src/app/page.tsx index 8de752082d..8b7c78cec7 100644 --- a/examples/custom-server/src/app/page.tsx +++ b/examples/custom-server/src/app/page.tsx @@ -1,6 +1,7 @@ import React, { Fragment } from 'react' import { notFound } from 'next/navigation' +import { getPayloadClient } from '../getPayload' import { Page } from './../payload-types' import { Gutter } from './_components/Gutter' import { RichText } from './_components/RichText' @@ -8,11 +9,17 @@ import { RichText } from './_components/RichText' import classes from './page.module.scss' export default async function Home() { - const home: Page = await fetch( - `${process.env.NEXT_PUBLIC_SERVER_URL}/api/pages?where[slug][equals]=home`, - ) - .then(res => res.json()) - .then(res => res?.docs?.[0]) + const payload = await getPayloadClient() + const { docs } = await payload.find({ + collection: 'pages', + where: { + slug: { + equals: 'home', + }, + }, + }) + + const home = docs?.[0] as Page if (!home) { return notFound() diff --git a/examples/custom-server/src/getPayload.ts b/examples/custom-server/src/getPayload.ts new file mode 100644 index 0000000000..2c33560b26 --- /dev/null +++ b/examples/custom-server/src/getPayload.ts @@ -0,0 +1,61 @@ +import dotenv from 'dotenv' +import path from 'path' +import type { Payload } from 'payload' +import payload from 'payload' +import type { InitOptions } from 'payload/config' + +import { seed as seedData } from './seed' + +dotenv.config({ + path: path.resolve(__dirname, '../.env'), +}) + +let cached = (global as any).payload + +if (!cached) { + cached = (global as any).payload = { client: null, promise: null } +} + +interface Args { + initOptions?: Partial + seed?: boolean +} + +export const getPayloadClient = async ({ initOptions, seed }: Args = {}): Promise => { + if (!process.env.MONGODB_URI) { + throw new Error('MONGODB_URI environment variable is missing') + } + + if (!process.env.PAYLOAD_SECRET) { + throw new Error('PAYLOAD_SECRET environment variable is missing') + } + + if (cached.client) { + return cached.client + } + + if (!cached.promise) { + cached.promise = payload.init({ + mongoURL: process.env.MONGODB_URI, + secret: process.env.PAYLOAD_SECRET, + local: initOptions?.express ? false : true, + ...(initOptions || {}), + }) + } + + try { + cached.client = await cached.promise + + if (seed) { + payload.logger.info('---- SEEDING DATABASE ----') + process.env.PAYLOAD_DROP_DATABASE = 'true' + await seedData(payload) + process.env.PAYLOAD_DROP_DATABASE = 'false' + } + } catch (e: unknown) { + cached.promise = null + throw e + } + + return cached.client +} diff --git a/examples/custom-server/src/server.ts b/examples/custom-server/src/server.ts index 727ca6e990..d9b2de20f1 100644 --- a/examples/custom-server/src/server.ts +++ b/examples/custom-server/src/server.ts @@ -8,28 +8,23 @@ dotenv.config({ }) import express from 'express' -import payload from 'payload' -import { seed } from './seed' +import { getPayloadClient } from './getPayload' const app = express() const PORT = process.env.PORT || 3000 const start = async (): Promise => { - await payload.init({ - secret: process.env.PAYLOAD_SECRET || '', - mongoURL: process.env.MONGODB_URI || '', - express: app, - onInit: () => { - payload.logger.info(`Payload Admin URL: ${payload.getAdminURL()}`) + const payload = await getPayloadClient({ + initOptions: { + express: app, + onInit: async newPayload => { + newPayload.logger.info(`Payload Admin URL: ${newPayload.getAdminURL()}`) + }, }, + seed: process.env.PAYLOAD_SEED === 'true', }) - if (process.env.PAYLOAD_SEED === 'true') { - payload.logger.info('---- SEEDING DATABASE ----') - await seed(payload) - } - if (process.env.NEXT_BUILD) { app.listen(PORT, async () => { payload.logger.info(`Next.js is now building...`)