Widget Backend

With widget backend support user can create HTTP endpoints in Console backend. They allow to define specific actions when endpoint is called. There can be used helper services not available in widget frontend.

Example of working widget with backend can be found here.

Security Aspects

Defining Endpoints

To create endpoint per widget you need to create backend.js file with at least one endpoint definition. That file must be placed in widget main folder similarly to widget.js file.

backend.js file structure

Example of backend.js file is presented below:

module.exports = function(r) {

    r.register('manager', 'GET', (req, res, next, helper) => {
        let _ = require('lodash');
        let jsonBody = require('body/json');
        let url = req.query.endpoint;
        let params = _.omit(req.query, 'endpoint');
        let headers = req.headers;

        jsonBody(req, res, function (error, body) {
            helper.Manager.doPost(url, params, body, headers)
                .then((data) => res.send(data))
                .catch(next);
        })
    });
}

backend.js file should export a function taking one argument (r in example). This function’s body contains calls to register method (r.register in example). Each call registers HTTP endpoint in the backend.

Syntax of register method:

function register(name, method, body)

where

Helper Services

In this section helper services, which can be used from helper object in endpoints body are described.

Logger

This service has no methods. You can just call

const logger = helper.Logger('my_endpoint');

to get WinstonJS logger object using provided string (my_endpoint) as logger category. Check out WinstonJS site to learn about this logger.

Manager

Available methods:

where:

Request

Available methods:

where:

Calling Endpoints

Previously defined endpoints can be accessed in widget frontend using toolbox.getWidgetBackend() method (see getWidgetBackend() for details).

Example of calling endpoint status with GET method widget.js:


Stage.defineWidget({
    // ... all stuff necessary to define widget ...

    fetchData: function(widget, toolbox, params) {
        return toolbox.getWidgetBackend().doGet('status')
            .then((data) => Promise.resolve({status: data}))
            .catch((error) => Promise.reject('Error fetching status. Error: ' + error));
    },

    render: function(widget,data,error,toolbox) {
        let status = data ? data.status : 'unknown';
        return (
            <p>
                Status: <b>{status}</b>
            </p>
        );
    }
});

The status endpoint for GET method must be defined in backend.js file:

module.exports = function(r) {
    r.register('status', 'GET', (req, res, next, helper) => {
        res.send('OK');
    });
}