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
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.
When you add the payload processer a pop-up opens presenting the editor.
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.
interface {
Set: (k: string, v: unknown) => void;
Get: (k: string) => unknown;
}
This is the entire HTTP request object. Refer to the GO documentation for details regarding the signature. |
|||
Integration gateway configuration. Refer to the source for details.
|
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.