Middleware

Sometimes you may want to customize the behaviour of BlinkDB when methods like insert, update, remove, or others are called. Perhaps you want to prevent all calls to remove (and instead soft delete records), or you’d like to log all actions taken, or you just simply want to intercept all calls to a certain function.

This is all quite simple with a call to use():

use(userTable, async (ctx) => {
  // Execute code before calling the implementation
  console.log(ctx.action); // Log the method called
  console.log(ctx.params); // Log parameters given to the method

  // Call the native implementation
  const result = await ctx.next(...ctx.params);

  // Execute code after the implementation
  console.log("Everything worked!");

  // Don't forget to return the result ;)
  return result;
})

More info about how hooks work can be found in the reference.

Modifying parameters

Hooks allow you to modify parameters passed to BlinkDB functions.

As an example, you can make sure that count will always prefer performance to accuracy:

use(userTable, async (ctx) => {
  if(isAction(ctx, "count")) {
    // Always pass `{ exact: false }` as an option to `count`
    return ctx.next(ctx.params[0], ctx.params[1], { exact: false });
  }
  return ctx.next(...ctx.params);
})

Modifying return values

Just like you can change the objects you pass to ctx.next(), you can also modify the return value:

use(userTable, async (ctx) => {
  if(isAction(ctx, "count")) {
    // `count(...)` will now always return 10 users more than we actually have
    const num = await ctx.next(...ctx.params);
    return num + 10;
  }
  return ctx.next(...ctx.params);
})
blinkDB © 2023