Using serverless platforms to implement reusable functions means you will often want to invoke one action from another. IBM Cloud Functions provides a RESTful API to invoke actions programmatically.
Rather than having to manually construct the HTTP requests to invoke actions from within the IBM Cloud Functions runtime, client libraries are pre-installed to make this easier.
These libraries make it simple to invoke other actions, fire triggers and access all other platform services.
Let's look an example of creating a "proxy" action which invokes another action (i.e, our hello action) if a "password" is present in the input parameters.
-
Create the following new action named
proxyfrom the following source files.var openwhisk = require('openwhisk'); function main(params) { if (params.password !== 'secret') { throw new Error("Password incorrect!") } var ow = openwhisk(); return ow.actions.invoke({name: "hello", blocking: true, result: true, params: params}) }
ibmcloud fn action create proxy proxy.js
{% hint style="info" %} Note The function uses the NPM Apache OpenWhisk JavaScript library which is pre-installed in the IBM Cloud Functions runtime (so you do not need to package it). Its source code can be found here: https://github.com/apache/openwhisk-client-js/. {% endhint %}
-
Invoke the proxy with an incorrect password.
ibmcloud fn action invoke proxy -p password wrong -r
{ "error": "An error has occurred: Error: Password incorrect!" }
{% hint style="tip" %}
Note On the invoke call above, we used the short form for the --result flag which is -r.
{% endhint %}
-
Invoke the proxy with the correct password.
ibmcloud fn action invoke proxy -p password secret -p name Bernie -p place Vermont -r
{ "greeting": "Hello Bernie from Vermont" } -
Review the activations list to show both actions were invoked.
ibmcloud fn activation list -l 2
Activation ID Kind Start Duration Status Entity 8387302c81dc4d2d87302c81dc4d2dc6 nodejs:10 cold 35ms success hello:0.0.4 e0c603c242c646978603c242c6c6977f nodejs:10 cold 438ms success proxy:0.0.1
{% hint style="tip" %}
Note On the invoke call above, we used the short form for the --last flag which is -l with a parameter to only list the last 2 activations.
{% endhint %}
{% hint style="success" %} 🎉Congrats on proxying an action! Be sure to check out all the cool things the NPM OpenWhisk JavaScript library can be used for such "invoking triggers" to fire events and "chaining action calls" within actions.🎉 {% endhint %}