I want to mess around with Payload, kind of like a REPL. Or, alternatively, put what I want in a script and run that instead. Currently, I put my stuff in
server.ts
, then run Payload as I normally would. But that's a bit slower and also hangs, because the server continues listening.
Is there a way to just run something and have Payload exit immediately after that?
The best way to do this would be a stand-alone script that uses the local API. You'd run it with ts-node. Here is an example:
import payload from 'payload'
import path from 'path'
import dotenv from 'dotenv'
dotenv.config({
path: path.resolve(__dirname, '../.env'),
})
const { PAYLOAD_SECRET, MONGODB_URI } = process.env
const doAction = async (): Promise<void> => {
await payload.init({
secret: PAYLOAD_SECRET,
mongoURL: MONGODB_URI,
local: true,
})
// Use the Payload Local API: https://payloadcms.com/docs/local-api/overview#local-api
await payload.find({
collection: 'posts',
// where: {}
})
await payload.create({
collection: 'posts',
data: {},
})
}
doAction()
Essentially, it runs payload.init with
local: true
which bypasses loading anything unneeded for local API usage