Cloud Functions REST API:从zip文件创建新操作

时间:2018-12-15 15:56:31

标签: ibm-cloud ibm-cloud-functions

我正在尝试使用以下curl从zip文件并通过REST API创建一个nodejs函数:

curl --request PUT --url 'https://my:credentials@openwhisk.eu-gb.bluemix.net/api/v1/namespaces/mynamespace/actions/my_action_name?overwrite=true' --header 'accept: application/json' --header 'content-type: application/json' --data '{"annotations":[{"key":"exec","value":"nodejs:10"},{"key":"web-export","value":true}],"exec":{"kind":"nodejs:10","init":"./action.zip"},"parameters":[{"key":"message","value":"Hello World"}]}'

结果我得到一个错误:

"error":"The request content was malformed:\n'code' must be a string or attachment object defined in 'exec' for 'nodejs:10' actions"

是否可以通过示例从zip文件以及通过REST API创建新动作的示例?谢谢。

2 个答案:

答案 0 :(得分:2)

您必须对.zip文件进行 base64编码,然后将其作为code参数传递。我已经编写了一个shell脚本(bash)进行编码,还创建了一个名为“ action ”的操作。将脚本另存为create.sh并执行脚本./create.sh

#!/bin/sh
ACTION=action
ZIP=$ACTION.zip

base64 $ZIP | echo "\"$(cat)\"" | jq "{namespace:\"_\", name:\"$ACTION\", exec:{kind:\"nodejs:10\", code:., binary:true, main:\"main\"}}" | curl -X PUT -H "Content-Type:application/json"  -d @- https://USERNAME:PASSWORD@openwhisk.ng.bluemix.net/api/v1/namespaces/_/actions/$ACTION?overwrite=true

完整代码

app.js或index.js代码

function myAction(args) {
    const leftPad = require("left-pad")
    const lines = args.lines || [];
    return { padded: lines.map(l => leftPad(l, 30, ".")) }
}

exports.main = myAction;

package.json

{
  "name": "node",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "left-pad" : "1.1.3"
  }
}

运行npm install并压缩文件zip -r action.zip *

测试动作

ibmcloud fn action invoke --result action --param lines "[\"and now\", \"for something completely\", \"different\" ]"

答案 1 :(得分:1)

REST API for creating or updating a Cloud Functions actions is documented中的IBM Cloud Functions API docs。找出确切的curl / request语法的一种好方法是在详细模式(-v)中使用IBM Cloud Functions CLI。 CLI只是REST API的包装,在详细模式下,所有REST详细信息都会打印出来。

以下是可打印内容的相关部分:

Req Body
Body exceeds 1000 bytes and will be truncated
{"namespace":"_","name":"mytest/myaction","exec":{"kind":"nodejs:8","code":"UEsDBBQAAAAIAHJPhEzjlkxc8wYAAH8VAAALABwAX19tYWluX18ucHlVVAkAA+iFxFrohcRadXgLAAEE9AEAAAT0AQAAxVhtb9s2EP6uX8HRCCLBipb002DA69YkbYo17dZ0GwbDMGSKlrXJokfSToNh/313R+rNL2labJiK1iJ578/x7tTBgJ7A/QzYq8IuN3NmdbpYFIIZm9rC2EKYmiIYsB+1ynW6Ykqz1y9u2WWpNhl7uamELVTFrGJClaUUtha2LeQ9S6uMiVJVspYNgnDPWKVhb5lalqU2ZUXFUqZlmaKwtKTNeWpkzKp0JcsHdj

您需要将binary字段设置为true,并将zip内容包括为codecurl docs建议使用@filename引用您的zip文件:

  

如果要从文件读取内容,请使用<@filename>作为   内容。