Node.js Developer Guide
Other documentationsDemoCommunityGitHub
  • Forest Admin
  • Getting started
    • How it works
    • Quick start
    • Install
      • Create your agent
      • Expose an HTTP endpoint
        • For standalone agents
        • On Express
        • On Koa
        • On Fastify
        • On NestJS
      • Autocompletion & Typings
      • Troubleshooting
    • Migrating legacy agents
      • What's new
      • Pre-requisites
      • Recommendations
      • Migration steps
        • Run new agent in parallel
        • Configure database connection
        • Code transformations
          • API Charts
          • Live Queries
          • Smart Charts
          • Route overrides
          • Smart Actions
          • Smart Fields
          • Smart Relationships
          • Smart Segments
        • Compare schemas
        • Swap agents
      • Post-migration
        • Dropping Sequelize
        • Optimize your agent
  • Data Sources
    • Getting Started
      • Collection selection
      • Naming conflicts
      • Cross-data source relationships
      • Query interface and Native Queries
        • Fields and projections
        • Filters
        • Aggregations
    • Provided data sources
      • SQL (without ORM)
      • Sequelize
      • Mongoose
      • MongoDB
    • Write your own
      • Replication strategy
        • Persistent cache
        • Updating the replica
          • Scheduled rebuilds
          • Change polling
          • Push & Webhooks
        • Schema & References
        • Write handlers
      • Translation strategy
        • Structure declaration
        • Capabilities declaration
        • Read implementation
        • Write implementation
        • Intra-data source Relationships
      • Contribute
  • Agent customization
    • Getting Started
    • Actions
      • Scope and context
      • Result builder
      • Static Forms
      • Widgets in Forms
      • Dynamic Forms
      • Form layout customization
      • Related data invalidation
    • Charts
      • Value
      • Objective
      • Percentage
      • Distribution
      • Leaderboard
      • Time-based
    • Fields
      • Add fields
      • Move, rename and remove fields
      • Override binary field mode
      • Override writing behavior
      • Override filtering behavior
      • Override sorting behavior
      • Validation
    • Hooks
      • Collection hook
      • Collection override
    • Pagination
    • Plugins
      • Provided plugins
        • AWS S3
        • Advanced Export
        • Flattener
      • Write your own
    • Relationships
      • To a single record
      • To multiple records
      • Computed foreign keys
      • Under the hood
    • Search
    • Segments
  • Frontend customization
    • Smart Charts
      • Create a table chart
      • Create a bar chart
      • Create a cohort chart
      • Create a density map
    • Smart Views
      • Create a Map view
      • Create a Calendar view
      • Create a Shipping view
      • Create a Gallery view
      • Create a custom tinder-like validation view
      • Create a custom moderation view
  • Deploying to production
    • Environments
      • Deploy on AWS
      • Deploy on Heroku
      • Deploy on GCP
      • Deploy on Ubuntu
      • Deploy on Azure
    • Development workflow
    • Using branches
    • Deploying your changes
    • Forest Admin CLI commands
      • init
      • login
      • branch
      • switch
      • set-origin
      • push
      • environments:create
      • environments:reset
      • deploy
  • Under the hood
    • .forestadmin-schema.json
    • Data Model
      • Typing
      • Relationships
    • Security & Privacy
Powered by GitBook
On this page
  • Code cheatsheet
  • Steps
  • Step 1: Calling addAction for the appropriate collection
  • Step 2: Porting the form definition
  • Step 3: Porting the route to the new agent execute function
  • Step 4: Porting Smart Action hooks

Was this helpful?

  1. Getting started
  2. Migrating legacy agents
  3. Migration steps
  4. Code transformations

Smart Actions

PreviousRoute overridesNextSmart Fields

Last updated 7 months ago

Was this helpful?

This is the official documentation of the @forestadmin/agent Node.js agent.

In legacy agents declaring a Smart Action was a two-step process:

  • First, you had to declare by changing the parameters of the collection function in the appropriate collections/*.js file.

  • Then, you had to implement the action by creating a route handler in the appropriate routes/*.js file.

    In the new agent, the process is simplified to a single step.

You can find the full documentation of action customization .

Code cheatsheet

Legacy agent
New agent

type: 'single' type: 'bulk' type: 'global'

scope: 'Single' scope: 'Bulk' scope: 'Global'

download: true

generateFile: true

reference: 'otherCollection.id'

{ type: 'Collection', collectionName: 'otherCollection' }

enums: ['foo', 'bar']

{ type: 'Enum', enumValues: ['foo', 'bar'] }

Request object

context.getRecordIds()

res.send(...)

return resultBuilder.success(...) return resultBuilder.error(...) ...

Steps

Step 1: Calling addAction for the appropriate collection

Start by calling the addAction function on the appropriate collection and passing the appropriate parameters.

Most notably, you will need to pass:

  • type should become scope

    • Note that the values are now capitalized (e.g. single becomes Single)

    • Legacy agents defaulted to 'bulk' if no type was specified. The new agent requires you to specify the scope.

  • download should become generateFile. This is still a boolean and the same value can be passed.

  • endpoint and httpMethod should be removed. The agent will now automatically handle the routing.

collection('companies', {
  actions: [
    {
      name: 'Mark as Live',
      type: 'bulk',
      download: false,
      endpoint: '/forest/actions/mark-as-live',
    },
  ],
});
agent.customizeCollection('companies', companies => {
  companies.addAction('Mark as Live', {
    scope: 'Bulk',
    execute: async (context, resultBuilder) => {},
  });
});

Step 2: Porting the form definition

Forms are now defined in the form property of the action.

You can simply copy the field's definition from the legacy agent to the new agent with the following differences:

  • fields should become form.

  • widget choice is no longer supported. A default widget will be used depending on the field type.

  • hook can be removed, those will be handled by the new agent automatically.

  • reference no longer exists. Use { type: 'Collection', collectionName: '...' } instead.

  • enums no longer exist. Use { type: 'Enum', enumValues: ['...'] } instead.

collection('customers', {
  actions: [
    {
      name: 'Charge credit card',
      type: 'single',
      fields: [
        {
          field: 'amount',
          isRequired: true,
          description: 'The amount (USD) to charge the credit card. Example: 42.50',
          type: 'Number',
        },
      ],
    },
  ],
});
agent.customizeCollection('customers', companies => {
  companies.addAction('Charge credit card', {
    // [...]
    form: [
      {
        field: 'amount',
        isRequired: true,
        description: 'The amount (USD) to charge the credit card. Example: 42.50',
        type: 'Number',
      },
    ],
  });
});

Step 3: Porting the route to the new agent execute function

In the legacy agent, users had to implement the action by creating a route handler in the appropriate routes/*.js file.

This is no longer needed as the new agent provides a context object that contains all the information that is needed to implement the action.

When porting the route handler to the new agent, you will need to:

  • Move the body of the route handler to the execute function of the action.

  • Replace RecordsGetter.getIdsFromRequest() call with context.getRecordIds().

router.post(
  '/actions/mark-as-live',
  permissionMiddlewareCreator.smartAction(),
  (req, res) => {
    const recordsGetter = new RecordsGetter(companies, request.user, request.query);

    return recordsGetter
      .getIdsFromRequest(req)
      .then(companyIds =>
        companies.update({ status: 'live' }, { where: { id: companyIds } }),
      )
      .then(() => res.send({ success: 'Company is now live!' }));
  },
);
agent.customizeCollection('companies', companies => {
  companies.addAction('Mark as Live', {
    // ...
    execute: async (context, resultBuilder) => {
      const companyIds = await context.getRecordIds();
      await companies.update({ status: 'live' }, { where: { id: companyIds } });

      return resultBuilder.success('Company is now live!');
    },
  });
});

Step 4: Porting Smart Action hooks

Load hooks and change hooks have been replaced on the new agent by the possibility to use callbacks in the form definition.

Here is an example of a load hook where the default value of a field is set to 50 euros converted into dollars:

collection('customers', {
  actions: [
    {
      name: 'Charge credit card',
      type: 'single',
      fields: [{ field: 'amount', type: 'Number' }],

      // Here is the load hook that sets the default value of the amount field to
      // 50 euros converted into dollars
      hooks: {
        load: async ({ fields, request }) => {
          const amountField = fields.find(field => field.field === 'amount');
          amountField.value = await convertEurosIntoDollars(50);
          return fields;
        },
      },
    },
  ],
});
agent.customizeCollection('customers', companies => {
  companies.addAction('Charge credit card', {
    scope: 'Single',
    form: [
      {
        field: 'amount',
        type: 'Number',

        // Set the default value of the amount field to 50 euros in dollars.
        // `convertEurosIntoDollars` is a function that returns a promise, it will be
        // awaited automatically
        defaultValues: () => convertEurosIntoDollars(50),
      },
    ],
  });
});

And another for a change hook which makes a field required if the value of another field is greater than 100:

collection('customers', {
  actions: [
    {
      name: 'Charge credit card',
      type: 'single',
      fields: [
        { field: 'amount', type: 'Number', hook: 'onAmountChange' },
        { field: 'motivation', type: 'String', isRequired: false },
      ],

      // Change hook requires the motivation field when amount is greater than 100
      hooks: {
        change: {
          onAmountChange: async ({ fields, request }) => {
            const amountField = fields.find(f => f.field === 'amount');
            const motivationField = fields.find(f => f.field === 'motivation');

            motivationField.isRequired = amountField.value > 100;

            return fields;
          },
        },
      },
    },
  ],
});
agent.customizeCollection('customers', companies => {
  companies.addAction('Charge credit card', {
    scope: 'Single',
    form: [
      { field: 'amount', type: 'Number' },
      {
        field: 'motivation',
        type: 'String',
        isRequired: context => context.formValues.amount > 100,
      },
    ],
  });
});

Replace res.send(...) calls with return resultBuilder.success() or return resultBuilder.error(), or the .

here
appropriate resultBuilder method