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.

Custom endpoint sends back localized fields

default discord avatar
NH02last year
8

I'm working with a custom endpoint for one of my collections:


...
endpoint: [{
...
handler: async (req, res) => {
        const { payload, query } = req;

        const teamMembers = {
          docs: await payload.collections['team-members'].Model.find()
            .sort({
              order: -1,
              lastNameWithoutPrefix: 1,
            })
            .limit(parseInt(query.limit as string))
            .skip(
              (parseInt(query.page as string) - 1) *
                parseInt(query.limit as string),
            ),
        };
        return res.status(200).send(teamMembers);
     },
...
}]


It sends all items from my collection back, however what I noticed is that the data for localized fields comes back as:

localizedField: {nl: 'string value'}


Normally payload sends the string back as

localizedField: 'string value'

. Is there a way to tell the custom endpoint to do this as well?

  • default discord avatar
    notchrlast year

    @NH02 what if you specify the

    locale

    property on the find request



    Does that then deliver the string value?

  • discord user avatar
    jmikrut
    last year

    so, because you're using the Mongoose model directly (and not the Payload

    find

    operation) Mongoose is just sending back the raw document itself (including all locales). Payload's operations are responsible for the localization "flattening", not Mongoose. If I were you, I'd try to leverage the Payload local api instead of the raw Mongoose model. But if you can't do that, you could always run the Payload

    afterRead

    field hooks manually against the documents that are returned from Mongoose



    here is where we "flatten" locales within the Payload core itself:



    https://github.com/payloadcms/payload/blob/master/src/collections/operations/find.ts#L192


    notice how we pass in the raw Mongoose docs?



    once they come back out, they will have locales "flattened". The

    locale

    is set on the

    req

    and then the

    afterRead

    hook is what looks at that, and then flattens the locales into the locale you ask for via the query param

    ?locale=myLocale
  • default discord avatar
    NH02last year

    Alright it works! Thank you 🙆‍♂️ @jmikrut

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..