Like what we’re doing? Star us on GitHub!

How to run a REPL or one-off script?

dodov
4 weeks ago
2

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?

  • denolfe
    Payload Team
    4 weeks 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

Open the post
Continue the discussion in Discord
Can't find what you're looking for?
Get help straight from the Payload team with an Enterprise License.Learn More