How to update current document in afterRead hook?

default discord avatar
christian-reichart
9 months ago
2 1

Merry Christmas to you all!

Here is a problem I currently have:
I'm trying to use Payload to sort of "cache" data from an external API and refetch it after a certain amount of time.

Setup:

const MyGlobal: GlobalConfig = {
  slug: 'my-global',
  fields: [
          {
            name: 'apiRequestKey',
            type: 'text',
            hooks: {
              beforeChange: [populateData],
              afterRead: [populateData],
            },
          }
          {
            name: 'updatedAt',
            type: 'date',
            admin: {
              hidden: true,
            },
          },
          {
            name: 'apiData',
            type: 'number',
            admin: {
              hidden: true,
            },
          },
  ]
}

Inside the hook, I check if updatedAt is expired, and refetch the apiData from an external API. Now if I try to use the local API with payload.updateGlobal() to write the new data and current timestamp in the database, the update function will trigger the afterRead hook again, before the data is changed, causing an infinite loop.

Possible solutions would be:

  • To use a separate collection which stores the updatedAt timestamp, but this could cause some race coditions
  • To somehow detect the request that is coming from inside the hook (I tried overwriting the user, but this doesn't work it seems)
  • To have some ability to disable/overwrite hooks/field hooks when using the local API (I think this is currently not possible)

Does anybody have an idea for an elegant solution to this problem? Any help is appreciated.

  • default discord avatar
    christian-reichart
    9 months ago

    I solved it for now using an early return with

    req.payloadAPI === 'local' && operation === 'read'
    

    However, I would still be interested in suggestions for other solutions, since the potential for an endless loop is still present, if the data changes in a specific way. I would still prefer to be able to disable hooks on the update call.

Open the post
Continue the discussion in GitHub
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.