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
  • Default behavior
  • Custom notifications
  • HTML result
  • File generation
  • Redirections
  • Webhooks
  • Response headers

Was this helpful?

  1. Agent customization
  2. Actions

Result builder

PreviousScope and contextNextStatic Forms

Last updated 1 year ago

Was this helpful?

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

Actions can be configured to achieve different results in the GUI.

Most actions will simply perform work and display the default notification, however, other behaviors are possible:

  • (for instance to trigger a login in a third-party application)

Default behavior

The default behavior, when no exception is thrown in the handler is to display a generic notification.

agent.customizeCollection('companies', collection =>
  collection.addAction('Mark as live', {
    scope: 'Single',
    execute: async context => {
      // Not using the resultBuilder here will display the generic success
      // notification (as long as no exception is thrown)
    },
  }),
);

Custom notifications

When customizing the notification message, you can use the resultBuilder to generate different types of responses.

agent.customizeCollection('companies', collection =>
  collection.addAction('Mark as live', {
    scope: 'Single',
    execute: async (context, resultBuilder) => {
      const isLive = false; // Company is not live

      if (!isLive) {
        // The success method will display a success notification.
        return resultBuilder.success('Company is now live!');
      } else {
        // The error method will display an error notification.
        return resultBuilder.error('The company was already live!');
      }
    },
  }),
);

HTML result

You can also return an HTML page to give more feedback to the user who triggered the Action.

agent.customizeCollection('companies', collection =>
  collection.addAction('Charge credit card', {
    scope: 'Single',
    execute: async (context, resultBuilder) => {
      /* ... charge the credit card ... */
      const wasCharged = true; // the credit card was successfully charged

      if (wasCharged) {
        return resultBuilder.success('Success', {
          html: `
            <p class="c-clr-1-4 l-mt l-mb">
              \$${record.amount / 100} USD has been successfuly charged.
            </p>
            <strong class="c-form__label--read c-clr-1-2">Credit card</strong>
            <p class="c-clr-1-4 l-mb">**** **** **** ${record.source.last4}</p>
          `,
        });
      } else {
        return resultBuilder.error('An error occured', {
          html: `
            <p class="c-clr-1-4 l-mt l-mb">
              \$${record.amount / 100} USD has not been charged.
            </p>
            <strong class="c-form__label--read c-clr-1-2">Credit card</strong>
            <p class="c-clr-1-4 l-mb">**** **** **** ${record.source.last4}</p>
            <strong class="c-form__label--read c-clr-1-2">Reason</strong>
            <p class="c-clr-1-4 l-mb">
              You can not charge this credit card. The card is marked as blocked
            </p>
          `,
        });
      }
    },
  }),
);

File generation

Because of technical limitations, Smart Actions that generate files should be flagged as such with the generateFile option.

This will cause the GUI to download the output of the action, but will also prevent from being able to use the resultBuilder to display notifications, errors, or HTML content.

Smart actions can be used to generate or download files.

The example code below will trigger a file download (with the file named filename.txt, containing StringThatWillBeInTheFile using text/plain mime-type).

collection.addAction('Download a file', {
  scope: 'Global',
  // This option is required to trigger the file download.
  generateFile: true,

  execute: async (context, resultBuilder) => {
    const random = Math.random();

    if (random < 0.33) {
      // Files can be generated from JavaScript strings.
      return resultBuilder.file(
        'StringThatWillBeInTheFile',
        'filename.txt',
        'text/plain',
      );
    } else if (random < 0.66) {
      // Or from a Buffer.
      const buffer = Buffer.from('StringThatWillBeInTheFile');
      return resultBuilder.file(buffer, 'filename.txt', 'text/plain');
    } else {
      // Or from a stream.
      const stream = fs.createReadStream('path/to/file');
      return resultBuilder.file(stream, 'filename.txt', 'text/plain');
    }
  },
});

Redirections

To streamline your operation workflow, it could make sense to redirect to another page after an Action has successfully been executed.

It is possible using the redirectTo function.

The redirection works both for internal (\*.forestadmin.com pages) and external links.

agent.customizeCollection('companies', collection =>
  collection.addAction('Mark as live', {
    scope: 'Single',
    execute: async (context, resultBuilder) => {
      return resultBuilder.redirectTo(
        '/MyProject/MyEnvironment/MyTeam/data/20/index/record/20/108/activity',
      );
    },
  }),
);
agent.customizeCollection('companies', collection =>
  collection.addAction('Mark as live', {
    scope: 'Single',
    execute: async (context, resultBuilder) => {
      return resultBuilder.redirectTo(
        'https://www.royalmail.com/portal/rm/track?trackNumber=ZW924750388GB',
      );
    },
  }),
);

Webhooks

After an action you can set up an HTTP (or HTTPS) callback - a webhook - to forward information to other applications.

Note that the webhook will be triggered from the user's browser, so it will be subject to CORS restrictions.

Its intended use is often to perform a login on a third-party application or to trigger a background job on the current user's behalf.

agent.customizeCollection('companies', collection =>
  collection.addAction('Mark as live', {
    scope: 'Single',
    execute: async (context, resultBuilder) => {
      return resultBuilder.webhook(
        'http://my-company-name', // Webhook URL.
        'POST', // Webhook method (typically a POST).
        {}, // Webhook headers if needed.
        { adminToken: 'your-admin-token' }, // Webhook body (only JSON is supported).
      );
    },
  }),
);

Please note that the webhook function and the setHeader function operate independently and do not modify the same HTTP call. Webhook headers will be sent along with the webhook call, while setHeaders will modify directly the Action response headers.

Response headers

Sometimes you may want to setup custom response headers after action execution, the setHeader function is here to reach out this goal.

Before executing any end function described above, you should be able to add headers to the action response like the exemple below.

agent.customizeCollection('companies', collection =>
  collection.addAction('Mark as live', {
    scope: 'Single',
    execute: async (context, resultBuilder) => {
      return resultBuilder
        .setHeader('myHeaderName', 'myHeaderValue')
        .redirectTo(
          'https://www.royalmail.com/portal/rm/track?trackNumber=ZW924750388GB',
        );
    },
  }),
);

Invalidating related data
Displaying a notification with a custom message
Displaying HTML content in a side panel
Generating a file download
Redirecting the user to another page
Calling a webhook from the user's browser
Setting up response headers