duplicate via the rest api?

default discord avatar
Hendriklast year
12

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

  • default discord avatar
    thisisnotchrislast year

    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
    Hendriklast year

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

  • default discord avatar
    thisisnotchrislast year

    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
    Jarrodlast year

    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
    Hendriklast year

    yeah did exactly this

  • default discord avatar
    Jarrodlast year

    perfect

  • default discord avatar
    Hendriklast year

    thanks! 🙂

  • default discord avatar
    Jarrodlast year

    np 🙂

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

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