Bypass collection hook when using LocalAPI

default discord avatar
KasparTr
7 months ago
5

I need to auto-update one collection when another collection is edited (using relationship field to detect which collection to auto-update).


While Collection hooks are great for this business logic, it takes me into a circular loop where the auto-update itself triggers another round which is not wanted.



I could escape the logic inside to hook with some temp flags in the collection itself but this is prone to errors and not a very elegant solution.



Is there a way to tell the LocalAPI, when updating a collection, to bypass collection hooks?

  • default discord avatar
    thgh
    7 months ago

    I would add

    cascade

    in the request and filter that out in the hook so it doesn't make it to the db.


    Not aware of a way to disable hooks.


    Eagerly waiting for relational databases 👀

  • default discord avatar
    KasparTr
    7 months ago

    What is cascade in request? How can I add that?

  • default discord avatar
    thgh
    7 months ago

    I meant a field named cascade with type boolean or text.


    { name: "cascade", type: "text", hidden: true }

    When doing the auto-update from the other collection, pass in a value so that the other collection knows not to start a circular loop


    hooks: {
      beforeChange: [({ data: { cascade, ...data }, req }) => {
        if (cascade !== 'ignore')
          req.payload.update({
            collection: "other",
            data: {
              cascade: "ignore",
              dependentValue: calculate()
             }
          })
        // Same as initial data except "cascade" is missing
        return data
      }],
    }


    It's probably what you described as the not very elegant solution 😛

  • default discord avatar
    KasparTr
    7 months ago

    I see, thank that is an interesting hack.


    The main problem with this approach, is that when you turn cascade off, you also need to make sure it turns back on after the operation has finished.



    Turning cascade on and off are also collection updates so now you have to deal with cascade update triggering the hooks also.



    I implemented this and it somehow works, through additional hacks, but I wouldn't show this code to anyone nor can I sleep at night 😄

  • default discord avatar
    thgh
    6 months ago

    The beforeChange hook runs before it hits the database, so cascade is actually never saved.



    By returning a value from the beforeChange hook, it will remove the cascade property from the input.

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.