Git Product home page Git Product logo

fc-nodejs-sdk's Introduction

fc-nodejs-sdk

NPM version build status coverage

Documents: http://doxmate.cool/aliyun/fc-nodejs-sdk/api.html

Notice

We suggest using fc2,The main difference between fc and fc2 is:

The response returned by the user is the following object.

{
     'headers': headers,
     'data': data,
}

for invoke function, data is the results returned by your code. By default, data is decoded by utf8, if you would like to get raw buffer, just set {rawBuf: true} in opts when you invoke function.

Examples are shown in the code below, for other apis, data is object.

Install the official fc2 release version:

npm install @alicloud/fc2 --save

Install oldVersion

fc version is in 1.x branch, you can install fc use 'npm' like this

npm install @alicloud/fc --save

License

MIT

Examples

Promise

'use strict';

var FCClient = require('@alicloud/fc2');

var client = new FCClient('<account id>', {
  accessKeyID: '<access key id>',
  accessKeySecret: '<access key secret>',
  region: 'cn-shanghai',
  timeout: 10000 // Request timeout in milliseconds, default is 10s
});

var serviceName = '<service name>';
var funcName = '<function name>';

client.createService(serviceName).then(function(resp) {
  console.log('create service: %j', resp);
  return client.createFunction(serviceName, {
    functionName: funcName,
    handler: 'index.handler',
    memorySize: 128,
    runtime: 'nodejs4.4',
    code: {
      zipFile: fs.readFileSync('/tmp/index.zip', 'base64'),
    },
  });
}).then(function(resp) {
  console.log('create function: %j', resp);
  return client.invokeFunction(serviceName, funcName, 'event');
}).then(function(resp) {
  console.log('invoke function: %j', resp);
}).catch(function(err) {
  console.error(err);
});

async/await (node >= 7.6)

'use strict';

const FCClient = require('@alicloud/fc2');

var client = new FCClient('<account id>', {
  accessKeyID: '<access key id>',
  accessKeySecret: '<access key secret>',
  region: 'cn-shanghai',
});

var serviceName = '<service name>';
var funcName = '<function name>';

async function test () {
  try {
    var resp = await client.createService(serviceName);
    console.log('create service: %j', resp);

    resp = await client.createFunction(serviceName, {
      functionName: funcName,
      handler: 'counter.handler',
      memorySize: 128,
      runtime: 'nodejs4.4',
      initializer: 'counter.initializer',
      code: {
        zipFile: fs.readFileSync('/tmp/counter.zip', 'base64'),
      },
    });
    console.log('create function: %j', resp);

    // by default , resp is decoded by utf8
    resp = await client.invokeFunction(serviceName, funcName, null);
    console.log('invoke function: %j', resp);

    // respWithBuf is returned as buffer if isRawBuf is set to be true in opts
    respWithBuf = await client.invokeFunction(serviceName, funcName, null, {}, 'LATEST', {rawBuf:true});

    uResp = await client.updateFunction(serviceName, funcName, {
      description: 'updated function desc',
      initializationTimeout: 60,
    });
    console.log('update function: %j', resp);
  } catch (err) {
    console.error(err);
  }
}
test().then();

Custom headers

We offer two ways to customize request headers.

One way is passing headers through the Client constructor. You should treat headers passed through the constructor as default custom headers, because all requests will use this headers.

var client = new FCClient('<account id>', {
  accessKeyID: '<access key id>',
  accessKeySecret: '<access key secret>',
  region: 'cn-shanghai',
  headers: {
    'x-fc-invocation-type': 'Async'
  }
});

await client.invokeFunction(serviceName, funcName, 'event');

Another way is passing headers through the function's parameter. You should use this way when you want to just pass headers in specific functions.

await client.invokeFunction(serviceName, funcName, 'event', {
  'x-fc-invocation-type': 'Async'
});

When both ways are used, headers will be merged. But for the headers with the same key, the headers provided by the function parameter overrides the headers provided by the constructor.

API Spec

See: https://help.aliyun.com/document_detail/52877.html

Test

ACCOUNT_ID=<ACCOUNT_ID> ACCESS_KEY_ID=<ACCESS_KEY_ID> ACCESS_KEY_SECRET=<ACCESS_KEY_SECRET> make test

fc-nodejs-sdk's People

Contributors

alifyb avatar alinode-oss avatar antsword avatar arlenmbx avatar blizzardzheng avatar chrisyip avatar cici503 avatar coco-super avatar fanzhe328 avatar jacksontian avatar ohyee avatar rocaltair avatar rockuw avatar rsonghuster avatar sang4lv avatar shuaichang avatar tanhe123 avatar vangie avatar wss-git avatar yinglixn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fc-nodejs-sdk's Issues

支持custom headers

FC有一些自定义的header,例如x-fc-invocation-type, x-fc-trace-id,需要SDK支持设置自定义的header。

Invoke error from frontend: required HTTP header Date was not specified

When I use this SDK to invoke my FC function, I got a 400 error, while do the POST request. it is said:

{"ErrorCode":"MissingRequiredHeader","ErrorMessage":"required HTTP header Date was not specified"}

And I checked the http.request method which automatically bundled by tool like parcel. Then I found, it's forbidden for frontend to do http request with date header (check MDN for more).

Is there any suggestion to me for invoking the FC function from frontend?

node SDK 调用函数异常

文档里写的地址是 POST /services/{serviceName.qualifier}/functions/{functionName} HTTP/1.1 。
但是 SDK 实际调用的是 /services/${getServiceName(serviceName, qualifier)}/functions/${functionName}/invocations

报错:

Error [FCundefinedError]: POST /services/xxxx/functions/xxxx/invocations failed with 400. requestid: undefined, message: undefined.
    at Client.request (/node_modules/@alicloud/fc2/lib/client.js:177:19)
    at processTicksAndRejections (internal/process/task_queues.js:95:5) {
  code: undefined
}

SignatureNotMatch

使用这个SDK的get()方法触发函数计算的任务,返回:

GET /proxy/script/exportBillExcel/ failed with 403. requestid: 36224761-90de-4299-8c63-f9d77c2306b9, message: The request signature we calculated does not match the signature you provided. Check your access key and signing method..

这个问题怎样解决?

函数调用-http 触发器

代码:

await client.invokeFunction('bff-service', 'getList', null);

错误提示:Function with http trigger(name: httpTrigger) can only be invoked with http trigger URL.

目前有方法调用http触发器的函数吗?

sourceArn必选字段?

我使用sdk创建一个云函数,绑定http触发器,但是http触发器并不调用oss之类的,这个sourceArn如何填写?
image
image

createFunction 函数 code 参数具体格式

  • createFunction
  • 创建Function
Options:

code function代码
code: {
     zipFile: fs.readFileSync(path.join(__dirname, 'figures/test.zip'), 'base64')
 }


请问 figures/test.zip 的目录结构?

{
   "errorMessage": "Module '/code/counter.js' is missing.",
   "errorType": "Error",
   "stackTrace": [
      "Error: Module '/code/counter.js' is missing."
   ]
} 

Return response headers in each API

我们有一些自定义的header返回,例如x-fc-error-type, x-fc-request-id, x-fc-log-result等。

当前接口返回的是response body,能否直接将response返回?

这样改动会有兼容性问题吗? @JacksonTian

没有设置预留函数容器数量的接口

/services/${getServiceName(serviceName, qualifier)}/functions/${functionName}/on-demand-config

这个接口,帮忙实现一下?因为没有文档,我只是本地简单测试了一下可用,希望维护者帮忙提交一下

java、golang里面有实现。

登录拦截怎么做,比如某些接口必须登录才可以调用。

我以前使用 aws 的lambda,它可以自定义授权,比如授权函数为 A 而B 需要授权,那么调用B之前会先调用A,如果A 里授权错误 会终止,授权成功会把自定义的数据传递给B

我现在需要把 aws 的代码部署到 阿里云来,目前看来唯一的困惑是这个,阿里fc 是否支持这个功能?我们的其他服务等等已经在阿里云跑了,不想将这个服务单独放在 aws 或者整个迁移到 aws

这个是将错就错了吗?

fc-nodejs-sdk/lib/client.js

Lines 113 to 116 in e33d800

if (path.startsWith('/proxy/')) {
queriesToSign = query || {}
}
var signature = Client.getSignature(this.accessKeyID, this.accessKeySecret, method, `/${this.version}${path}`, headers, queriesToSign);

JavaScript 里 {} 直接用来判断,为true,所以这里的结果永远会在变量str后面加上一个可能没有意义的\n(也许是有意义的,但我用其他语言写这个签名算法时,参考本代码被误导,始终缺少一个\n,后来追这份代码,加上\n后,签名验证通过)。

var str = `${method}\n${contentMD5}\n${contentType}\n${date}\n${signHeaders}${pathUnescaped}`;
if (queries) {
var params = [];
Object.keys(queries).forEach(function(key) {
var values = queries[key];
var type = typeof values;
if (type === 'string') {
params.push(`${key}=${values}`);
return;
}
if (Array.isArray(values)) {
queries[key].forEach(function(value){
params.push(`${key}=${value}`);
});
}
});
params.sort();
str += '\n' + params.join('\n');
}

如果有意义,是否可以将代码稍作修改,将 line 57的第一个\n移动到 line 39的末尾?

config `timeout` didn't work

github:
client.js Line 90
this.timeout = Number.isFinite(config.timeout) ? config.timeout : 10000; // default is 10s

But, install version 1.2.0 code from npm, the code is
this.timeout = 10000; // 10s

`invokeFunction` not work as expected when request includes certain characters such as `@` and `/`

var FCClient = require('@alicloud/fc2');

var client = new FCClient('xxxx', {
  accessKeyID: 'xxx',
  accessKeySecret: 'xxx',
  region: 'cn-shanghai',
  timeout: '180000', // 配置超时
});

client
  .invokeFunction(
    'xxxxx',
    'runScript',
    JSON.stringify({
      func: '{ headers: request.hello }',
      request: {
        hello: '@alipay/b' // #1
      }
    })
  )
  .then(resp => {
    console.log('resp', resp);
  })
  .catch(err => {
    // TODO
    console.error('err', err);
  });

返回

resp { headers:
   { 'access-control-expose-headers': 'Date,x-fc-request-id,x-fc-error-type,x-fc-code-checksum,x-fc-invocation-duration,x-fc-max-memory-usage,x-fc-log-result,x-fc-invocation-code-version',
     'content-length': '2',
     'content-type': 'application/octet-stream',
     'x-fc-code-checksum': '10424674220137372625',
     'x-fc-invocation-duration': '5',
     'x-fc-invocation-service-version': 'LATEST',
     'x-fc-max-memory-usage': '25.18',
     'x-fc-request-id': '528c084a-ab72-428f-ae96-0ac3e21e70ce',
     date: 'Tue, 24 Dec 2019 06:32:49 GMT' },
  data: '{}' }

期望返回:

resp { headers:
   { 'access-control-expose-headers': 'Date,x-fc-request-id,x-fc-error-type,x-fc-code-checksum,x-fc-invocation-duration,x-fc-max-memory-usage,x-fc-log-result,x-fc-invocation-code-version',
     'content-length': '22',
     'content-type': 'application/octet-stream',
     'x-fc-code-checksum': '10424674220137372625',
     'x-fc-invocation-duration': '5',
     'x-fc-invocation-service-version': 'LATEST',
     'x-fc-max-memory-usage': '25.10',
     'x-fc-request-id': '528977c4-b946-4e9a-a325-e9ee9c0def78',
     date: 'Tue, 24 Dec 2019 06:28:42 GMT' },
  data: '{"headers":"@alipay/b"}' }

注意 data 部分。

当把 #1 行代码从 @alipay/b 改成 @alipay/,返回才符合预期。

创建服务Client.createService时 传入参数 vpcConfig 报错400 - Argument 'vpcConfig' is not supported

创建service时 传入参数 vpcConfig 报错400 - Argument 'vpcConfig' is not supported。
我已经根据 阿里云官网文档来做的
API文档
FC文档

代码:

vpcConfig = { 'securityGroupId':'sg-1111', 'vSwitchIds':['vsw-1111'], 'vpcId':'vpc-1111 }
service = await fc.createService(serviceName, { description: serviceDescription, vpcConfig: vpcConfig });

报错

{"ErrorCode":"InvalidArgument","ErrorMessage":"Argument 'vpcConfig' is not supported"}

SDK debug跟踪

/2016-08-15/services +4ms
lambda request headers: {"accept":"application/json","date":"Fri, 15 Jun 2018 03:22:03 GMT","host":"111111111.cn-shenzhen.fc.aliyuncs.com","user-agent":"Node.js(v9.10.1) OS(darwin/x64) SDK(@alicloud/[email protected])","x-fc-account-id":"222222","content-type":"application/json","content-length":59,"content-md5":"11111111111=","authorization":"FC LTAIldIgp2DLHiGG="} +1ms
httpx > POST /2016-08-15/services HTTP/1.1 +14ms
httpx > accept: application/json +0ms
httpx > date: Fri, 15 Jun 2018 03:22:03 GMT +1ms
httpx > host: 111111.cn-shenzhen.fc.aliyuncs.com +0ms
httpx > user-agent: Node.js(v9.10.1) OS(darwin/x64) SDK(@alicloud/[email protected]) +0ms
httpx > x-fc-account-id: 111111111 +0ms
httpx > content-type: application/json +0ms
httpx > content-length: 59 +0ms
httpx > content-md5: MDJhZWRkM2M= +0ms
httpx > authorization: FC LTAIldI5dNkEtEi/RZw= +0ms
httpx > Connection: keep-alive +0ms
httpx > +0ms
httpx > +0ms
httpx < HTTP/1.1 400 Bad Request +0ms
httpx < access-control-allow-origin: +0ms
httpx < access-control-expose-headers: Date,x-fc-request-id,x-fc-error-type,x-fc-code-checksum,x-fc-max-memory-usage,x-fc-log-result,x-fc-invocation-code-version +1ms
httpx < content-type: application/json; charset=utf-8 +0ms
httpx < x-fc-error-type: FCCommonError +0ms
httpx < x-fc-request-id: 96-a60afc60d7b +0ms
httpx < date: Fri, 15 Jun 2018 03:22:03 GMT +0ms
httpx < content-length: 86 +0ms
lambda response status: 400 +0ms
lambda response headers: {"access-control-allow-origin":"","access-control-expose-headers":"Date,x-fc-request-id,x-fc-error-type,x-fc-code-checksum,x-fc-max-memory-usage,x-fc-log-result,x-fc-invocation-code-version","content-type":"application/json; charset=utf-8","x-fc-error-type":"FCCommonError","x-fc-request-id":"962b1-7afc60d7b","date":"Fri, 15 Jun 2018 03:22:03 GMT","content-length":"86"} +1ms
httpx +0ms
httpx {"ErrorCode":"InvalidArgument","ErrorMessage":"Argument 'vpcConfig' is not supported"} +0ms

lambda response body: {"ErrorCode":"InvalidArgument","ErrorMessage":"Argument 'vpcConfig' is not supported"} +0ms

FCInvalidArgumentError: POST /services failed with 400. requestid: 9625-7080, message: Argument 'vpcConfig' is not supported.
at Client.request (/Applications/mampstack-5.5.30-0/apache2/htdocs/ali-func/fcvpc/node_modules/.2.0.3@@alicloud/fc2/lib/client.js:148:19)
at
at process._tickCallback (internal/process/next_tick.js:118:7)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.