V8 custom scripting service add

From DreamFactory
Jump to: navigation, search
DreamFactoryTutorialsV8 custom scripting service add

You can create any number of custom scripting services and invoke them from the REST API. In this example we'll create a simple service that accepts two numbers as query parameters and returns their sum as the result. Since the script is a service, you can control access to it using roles. The script has whatever access to the API that is allowed by the role of the user calling the script. If allowed, the script can make additional REST API calls or cURL requests.

Create the service

Go to the services tab in the admin console and click Create. Set the Service Type to Custom Scripting Service. Set the service name to 'add'. Set the service label to 'Add'. Go to the Config tab for the new service and set the Script Engine Type to V8js. Set the Content to contain the following code then click Create Service.

var lodash = require("lodash.min.js");

if (event.request.method !== "GET") {
    throw("Only HTTP GET is allowed on this endpoint.");
}

var params = event.request.parameters;

// check for and add required params
var required = ["n1","n2"];
lodash._.each( required, function( element ) {
    if (!params.hasOwnProperty(element) || !params[element]) {
        throw( "Missing '" + element + "' in params\n" );
    }
});

var result = Number(params.n1) + Number(params.n2);
return result;

Call the service

From any REST client, do a GET on /api/v2/add?n1=4&n2=5 and you should get back the result of 9. In this case the result is just a number but it could also be a JSON payload. A simple REST client can be found at <your_instance_url>/test_rest.html. Remember if you are not an admin user your user role must allow access to the custom scripting service.