duplicate via the rest api?

default discord avatar
Hendrik
7 months ago
12

Did not find anything about this in the docs. Is it possible to duplicate a document via the rest api?

  • default discord avatar
    thisisnotchris
    7 months ago

    By default, I don't think so, but you can easily add a custom endpoint to your REST api.

    https://payloadcms.com/docs/rest-api/overview#custom-endpoints


    I imagine you'd look up an existing post by ID, then you would copy the field data and create a new post and let the ID populate.

  • default discord avatar
    Hendrik
    7 months ago

    @thisisnotchris yeah, have already done this, but thought it would be nice not to produce two endpoinst for the same behaviour 🙂

  • default discord avatar
    thisisnotchris
    7 months ago

    That's true, if the aren't any side effects, you could create a reusable utility to do this



    But i agree, built in duplicate would be nice



    🙂

  • default discord avatar
    Jarrod
    7 months ago

    Hey @Hendrik just catching up here. I think the custom endpoint is the right solution for now, we are not sure if this is something we will provide out of the box yet. A couple things you will want to keep in mind when doing this:


    const accessibleDoc = await payload.findByID({
      collection: 'pages',
      id: req.query.id,
      showHiddenFields: true,
      overrideAccess: false,
      user: req.user,
    })


    You will want to pass the user through, turn off the overrideAccess, and show hidden fields. Then you should check if a doc comes back, if it does, the user has access and should be allowed to duplicate, if not then the user does not have access and should return an error. You will want to include showHiddenFields so all fields are duplicated onto the new doc

  • default discord avatar
    Hendrik
    7 months ago

    yeah did exactly this

  • default discord avatar
    Jarrod
    7 months ago

    perfect

  • default discord avatar
    Hendrik
    7 months ago

    thanks! 🙂

  • default discord avatar
    Jarrod
    7 months ago

    np 🙂

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.