Route overrides

Route overrides ↗ allowed customizing the behavior of the routes exposed by the agent.

This very low-level feature was used to implement many use cases:

  • Attach handlers to events in the UI

  • Customize filtering, search and sort behaviors

  • Other advanced use cases.

Because our new agent API is higher-level, the protocol used to communicate between the agent and the application can no longer be manipulated.

Code cheatsheet

Examples

Add custom permissions

Custom permissions would better be implemented by using the Roles ↗ feature from the UI.

router.delete(
  '/companies/:recordId',
  permissionMiddlewareCreator.delete(),
  (request, response, next) => {
    const { params, query, user } = request;

    if (user.email !== 'sandro.munda@forestadmin.com) {
      response.status(403).send('This collection is protected, you cannot remove it.');
      return;
    }

    next();
  },
);

Add validation to fields

function handler(request, response, next) {
  const patch = request.body.data.attributes;

  if (path.name && /^Forest/.test(path.name)) {
    return "All company names should begin with 'Forest'.";
  }

  if (error) {
    response.status(400).send(error);
  } else {
    next();
  }
}

router.post('/companies', permissionMiddlewareCreator.create(), handler);
router.put('/companies/:id', permissionMiddlewareCreator.update(), handler);

Run code on UI events

// Override the POST /customers route
router.post('/customers', permissionMiddlewareCreator.create(), async (req, res, next) => {
  try {
    // Call an external API.
    await superagent.post('https://my-company/create-card').set('X-API-Key', '**********').end();

    // Calls next() to executes Forest Admin's default behavior
    next();
  } catch (err) {
    next(err);
  }
});

Last updated

Revision created on 5/31/2023