Flow to override the default CRUD

Context

• We’re a team using the nodejs agent.
• Myself have 5y+ experience overall on Forest, especially on the Ruby agent (new company from 0, we’ve decided to go on TypeScript and explain the nodejs agent selection)
• We’re architecture in micro-services and the back-office service is a read-only tool, databases connection are all connected with a read-replica
• Our backend services expose specific routes to interact with internal back-office resources

Feature(s) impacted

We want to override the default behavior of Forest to allow managing creation of resources to domain service (microservices architecture)
We’ve followed the doc section > Collection override | Node.js Developer Guide

Observed behavior

We’re pretty lost on the expected behavior of the code block. The documentation should help us to manage:
• How should the response look like? a JSON object? a Collection database fetched object?
• How to manage the errors part?

For info, we’re using axios to make HTTP requests to our backend service.

Expected behavior

collection_name.overrideCreate(async context => {
    const { data } = context;

    axios.post('http://backend.api/post-route', data[0])
      .then(response => {
        return [response.data]; // How should the response be formatted for Forest?
      })
      .catch(err => {
        console.log(err);
        return err; // How error(s) response should be formatted?
      });
  });

Context

  • Agent technology: nodejs
  • Agent (forest package) name & version: ^1.0.0
  • Database type: postgres

Hello @Maxime_D,

Glad to hear that you’re sticking with Forest Admin ! :evergreen_tree:

How should the response look like? a JSON object? a Collection database fetched object?

The handler function passed to the overrideCreate method should be typed properly:
(context: CreateOverrideCustomizationContext<S, N>) => Promise<TPartialSimpleRow[]>

It is the same type for data present in the context, e.g:

// In case of a customer collection
[
  { adress: "123 bd Mary", name: "John"... }
]

How to manage the errors part?

You can either use Error classes defined in @forestadmin/datasource-toolkit which is a dependancy of every @forestadmin datasources:

const { MissingFieldError } = require('@forestadmin/datasource-toolkit');
...
   .catch(err => {
       throw new MissingFieldError('favoriteColor', 'customer');
   });     

The second solution is to create your own errors and translate them globally via a function given to the agent .

Nevertheless the point you made is clear, I’ll update the documentation on the Collection override to provide examples.

Best regards,

2 Likes