I am new to OpenWhisk / IBM Cloud Functions. I was trying to build a basic chat bot application using IBM Watson Assistant. So what I have is a cloud functions action which is being invoked from my Node.js server, the action has all the credentials to interact with the Watson service, I am using "watson-developer-cloud" npm package as a dependency. Everything works as expected when I am run on local machine, however, when I zip the directory and upload it as an OpenWhisk web action it is not able to install the dependencies.
The procedure I followed is:
npm install
bx wsk action create chataction --kind nodejs:8 chatactionzip.zip
Can anyone help me get this working? I am uploading the screenshots of the directory structure.
package.json is like this
`
{
"name": "chataction",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"watson-developer-cloud": "^3.13.0"
}
}
`
this is my code (i am removing some credentials rest is as it is) `
const AssistantV1 = require('watson-developer-cloud/assistant/v1');
function main(params) {
var inputText = params.inputText || 'input was not sent';
//return {result: inputText}
var assistant = new AssistantV1({
username: '',
password: '',
url: '',
//api_key: '',
version: '2018-11-26'
});
var inputMessageParams = {
input: {
text: inputText
},
workspace_id: ''
}
assistant.message(inputMessageParams, function(err, result, response) {
if(err) {
console.log(err);
return {err: err}
}
else {
// console.log(response);
// console.log(response.body.output.text);
// console.log(response.data);
return {result: response.body.output.text[0]}
}
});
//return {notHit: 'npm not working'}
}
exports.main = main;
`
invoking code is like this `
const openwhisk = require('openwhisk');
options = {
apihost: 'openwhisk.eu-gb.bluemix.net',
api_key: ''
}
var ow = openwhisk(options);
var params = {inputText: 'Hello'}
var name = 'chataction';
var blocking = true;
var result = true;
ow.actions.invoke({name, blocking, result, params})
.then((result) => {
console.log(result);
});
`
Serverless Actions are async, you need to wrap your code in a Promise or use try/catch if the API your using already returning a Promise
You main function is ending before your method assistant.message()
call is done
return new Promise((resolve, reject) =>{
assistant.message(inputMessageParams, function(err, result, response) {
if(err) {
console.log(err);
reject({err: err})
}
else {
// console.log(response);
// console.log(response.body.output.text);
// console.log(response.data);
resolve( {result: response.body.output.text[0]})
}
});
});
More info on asynchronous javascript in the docs here: https://console.bluemix.net/docs/openwhisk/openwhisk_reference.html#openwhisk_ref_javascript