Skip to main content

Add your first Javascript Module

First, go to your file explorer and select the modules folder.

Then create a new file.

Name your file as you want. In our example we used the default name demo-module.js

Be careful : you need to use a js extension file.

Now, you will see a default template, you can edit it as you need.

After editing you can click on Push to Github button and add a commit' name.

Javascript Module example

/modules/hello.js
exports.on_backend_call = function(ctx) {
const name = (ctx.request.query.name && ctx.request.query.name[0]) ? ctx.request.query.name[0] : 'World';
return {
status: 200,
headers: {
'Content-Type': 'application/json'
},
body_json: { hello: name }
}
};

exports.on_response = function(ctx) {
const name = (ctx.request.query.name && ctx.request.query.name[0]) ? ctx.request.query.name[0] : 'World';
return {
...ctx.otoroshi_response,
headers: {
...ctx.otoroshi_response.headers,
'hello': name,
}
}
}

Configure your Javascript Module plugin in your openapi.json :

openapi.json
    "YOUR_PLUGIN_REF_NAME": [
{
"enabled": true,
"plugin": "cp:cloud-apim.plugins.JsModulePlugin",
"config": {
"module": "/modules/hello.js"
}
}
]

NO NEED MORE CONFIGURATION EXCEPT MODULE property

Here is a pre-built openapi file to use a Javascript Module

openapi.json
{
"openapi": "3.1.0",
"info": {
"title": "Javascript Module API",
"version": "1.0.0",
"description": "# Introduction\nWelcome to the reference for the Javascript Module API!",
"contact": {
"name": "Javascript Module API",
"url": "https://www.cloud-apim.com",
"email": "contact@cloud-apim.com"
},
"x-logo-none": {
"url": "https://www.cloud-apim.com/assets/logo/cloud-apim-logo-inverted.png"
}
},
"tags": [],
"paths": {
"/demo": {
"get": {
"tags": [],
"summary": "",
"operationId": "getJsDemo",
"x-cloud-apim-backend": {
"$ref": "#/components/x-cloud-apim-backends/jsdemobackend"
},
"x-cloud-apim-plugins": {
"$ref": "#/components/x-cloud-apim-plugins/jsdemoplugin"
}
}
}
},
"components": {
"x-cloud-apim-plugins": {
"jsdemoplugin": [
{
"enabled": true,
"plugin": "cp:cloud-apim.plugins.JsModulePlugin",
"config": {
"module": "/modules/hello.js"
}
}
]
},
"x-cloud-apim-backends": {
"jsdemobackend": {
"targets": [
{
"hostname": "jsonplaceholder.typicode.com",
"port": 443,
"tls": true
}
],
"root": "/",
"rewrite": false
}
}
}
}

Try it

Go to $YOUR_SERVERLESS_DOMAIN/$YOUR_ROUTE_PATH

You will see this result.

You can add a name query parameter such as $YOUR_SERVERLESS_DOMAIN/$YOUR_ROUTE_PATH?name=demo

in order to test your hello.js

And then, you can see that the response body changed as shown below :

{
'hello': 'demo'
}