How can I create a custom API endpoint with FindOne using slug?

default discord avatar
aayush2149 months ago
6

In my pages collection I have a slug field which is generated on submission


name: 'slug', label: 'Slug', type: 'text', index: true, admin: { position: 'sidebar', }, hooks: { beforeValidate: [formatSlug(fieldToUse)], },

In the same collection, I created a custom REST endpoint for finding by slug, it obviously returns a single document for the respective slug, but since it uses payload.find from the Local API it returns a paginated response. Is there a way to do a findOne in the Local API. What is the best approach for this?



endpoints: [ { path: "/slug/:slug", method: "get", handler: async (req, res, next) => { const data = await payload.find({ collection: 'pages', where: {slug:{equals:req.params.slug}}, limit:1 }) if (data) { res.status(200).send({ data }); } else { res.status(404).send({ error: "not found" }); } }, }, ],


Oh my God, I'm just finding the documentation for using

where

in the default REST API which means I don't need my custom endpoint. That said the problem remains the same, I get a paginated response with payload's default where API also

  • default discord avatar
    dr_mint9 months ago

    Change the end of your custom endpoint with


    if (data.docs.length === 0) {
      res.status(404).send({ error: "not found" });
    } else {
      res.status(200).send(data.docs[0]);
    }
  • default discord avatar
    ritsu04559 months ago

    just send first element of array in the response, or if not exists 404



    i still think it's a good case for custom endpoint, so your end user won't need to manually create query on each request and less data in the response

  • default discord avatar
    aayush2149 months ago

    That worked like a charm. Thank you. I still think payload Local API should add a findOne.

  • default discord avatar
    evanion5 months ago

    sorry to resurrect this old thread, but @AayushTheRefresher where is the

    formatSlug

    function coming from?

  • default discord avatar
    aayush2145 months ago

    Can't remember particularly but I think I wrote a utility function or maybe you can find it in one of the example repos that payload is maintaining.

  • default discord avatar
    evanion5 months ago

    OK, I just found a plugin that has a slug field (

    https://github.com/NouanceLabs/payload-better-fields-plugin/tree/master

    )


    checking it out now

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.