Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

How to run a REPL or one-off script?

default discord avatar
yandodov2 years ago
1

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?

  • discord user avatar
    denolfe
    2 years ago

    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

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.