Previous Values with Hooks

Hi,

I have a special use case for @forestadmin/agent:1.12.0, which I am not able to solve with the docs.

Desired behaviour: Send out an event to a 3rd-party service over HTTP, after editing a record & persistence to the database, with the previous values of the edited record.

As I understand:

  • I can only generate previous values in the Update-Before hook
  • I can only send out a http request upon database persistence using an After-hook.
  • I can’t pass data from a Before to its corresponding After hook.

Are these observations correct? Then I’m stuck. Do you see another way to achieve the desired behaviour?

Thanks in advance.

You are indeed stuck.

Let me make a PR around that

1 Like

I just made a PR (in review) to add a caller.requestId value so that you can reconcile calls to multiple hooks on the same request.

Once merged, you should be able to do the following:

  agent.customizeCollection('hubspot_contacts', collection => {
    // Use a weak map to avoid leaking memory if updates fail.
    const recordsBeforeByRequestId = new WeakMap();
    const hookColumns = ['the', 'columns', 'you', 'need', 'for', 'the', 'api'];

    collection.addHook('Before', 'Update', async context => {
      const recordsBefore = await context.collection.list(context.filter, hookColumns);

      recordsBeforeByRequestId.set(context.caller.requestId, recordsBefore);
    });

    collection.addHook('After', 'Update', context => {
      const recordsBefore = recordsBeforeByRequestId.get(context.caller.requestId);
      const recordsAfter = await context.collection.list(context.filter, hookColumns);

      // Call API here

    });
  });

PR URL: fix(agent): add request identifier to context.caller by romain-gilliotte · Pull Request #753 · ForestAdmin/agent-nodejs · GitHub

PR was merged

You should be good to go.
I added a ticket to our tracker so that we document that in the hooks documentation page

Thanks for the quick action! I upgraded to @forestadmin/agent:1.13.1, and the requestId is there.

But something went missing. From your example above:

  agent.customizeCollection('hubspot_contacts', collection => {
    // Use a weak map to avoid leaking memory if updates fail.
    const recordsBeforeByRequestId = new WeakMap();
    const hookColumns = ['the', 'columns', 'you', 'need', 'for', 'the', 'api'];

    collection.addHook('Before', 'Update', async context => {
      const recordsBefore = await context.collection.list...

The list and other functions are missing, when I debug. Typescript doesn’t complain.

Sorry, never mind. I’m wrong, it’s there.