You are reading the documentation for an outdated Corteza release. 2022.9 is the latest stable Corteza release.

Process Requests with JavaScript

The API GW processing filter includes support to process the request using arbitrary JavaScript code.

To process your requests using JavaScript, open the Admin web application, navigate to system  integration gateway and edit the endpoint you wish to define the code for.

Click on the processing tab in the filter list and select the payload processer option.

Annotated image

When you add the payload processer a pop-up opens presenting the editor.

Annotated image

Type in the JavaScript code snippet you wish to execute. The provided JavaScript code is automatically wrapped by a function with the signature of:

function (input: Scope): unknown {
  // {{snippet}}
}

To exemplify; the code snippet of return "Hello, world!" would become:

function (input) {
  return "Hello, world!"
}

The following example code snippet takes in the provided name and surname of our users and returns an array of fullname parameters.

// We firstly need to get the body of the request
var b = JSON.parse(readRequestBody(input.Get('request')));

return {
  // Assure correct casing
  "results":
    b.map(function({ name, surname }) {
        return {
          "fullname": name[0].toUpperCase() + name.substring(1) + " " + surname[0].toUpperCase() + surname.substring(1)
        }
    }),
  "count": b.length
};

The following cURL example invokes the above JavaScript function.

curl -X GET $BASE_URL/api/test-js \
  -H 'Content-Type: application/json' \
  -d '[{"name":"johnny","surname":"mnemonic"},{"name":"johnny","surname":"knoxville"}]';

Function Arguments

The code snippet receives a single argument, input, that contains the entire request.

The argument has the signature of:
interface {
  Set: (k: string, v: unknown) => void;
  Get: (k: string) => unknown;
}
Table 1. The input object parameters:

request

This is the entire HTTP request object. Refer to the GO documentation for details regarding the signature.

opts

Integration gateway configuration. Refer to the source for details.

DevNote generate above opt. docs

Function Result

The result of the JavaScript snippet is provided to the post filters that prepare and return an HTTP response.

When the result is a string, such as Hello, world!, the result is used as is.

When the result is a non-string value, such as { key: "value" }, the result is JSON encoded.

Built-in Function Reference

Function Signature Description Example

readRequestBody

readRequestBody(input: HttpRequest): string

The function returns the contents of the provided request object.

readRequestBody(input.Get('request')) returns the request’s body as a string