JavaScript 函数中的宿主服务

Nex 执行的 JavaScript 函数运行在一个 V8 沙盒中,该沙盒通常还被包含在 Firecracker 沙盒内。因此,这些 JavaScript 函数无法像其他函数类型(例如云提供商中的 Node.js)那样自由地访问各种功能。不过,我们通过 宿主服务 默认提供了最常见的使用场景。

宿主服务不仅仅是对任意功能的访问,而是对 经过管理 的功能的访问,这些功能经过预先配置并随时可用,因此函数开发者无需编写配置代码,只需专注于所需的功能抽象即可。

HTTP 客户端

如果您希望从您的函数中发起 HTTP 请求,可以使用 HTTP 客户端:

get = this.hostServices.http.get('https://example.org');

所有 HTTP 方法都以函数形式提供支持:

  • get
  • post
  • put
  • patch
  • del
  • head

键值存储

每个由 Nex 管理的 JavaScript 函数都可以访问一个键值存储抽象,该抽象内部由 NATS 键值存储桶支持。

this.hostServices.kv.set('hello', payload);
this.hostServices.kv.delete('hello');

this.hostServices.kv.set('hello2', payload);
return {
  keys: this.hostServices.kv.keys(),
  hello2: this.hostServices.kv.get('hello2')
}

请注意,您无需手动或显式地配置存储桶。您可以假设您的函数拥有自己的、隔离的存储桶,并且在多租户环境中是安全的。

对象存储

每个由 Nex 管理的函数都可以访问一个托管的对象存储。以下代码展示了 JavaScript 如何与该存储交互:

(subject, payload) => {
  this.hostServices.objectStore.put('hello', payload);
  this.hostServices.objectStore.delete('hello');

  this.hostServices.objectStore.put('hello2', payload);
  return {
    list: this.hostServices.objectStore.list(),
    hello2: String.fromCharCode(...this.hostServices.objectStore.get('hello2'))
  }
};

Core NATS 消息传递

JavaScript 函数在其触发主题上接收消息,这些主题在部署时指定。要发布消息或发起请求,宿主服务提供了对 Core NATS 的黑盒访问权限。

this.hostServices.messaging.publish('hello.world', payload);

req = this.hostServices.messaging.request('hello.world.request', payload);

reqMany = this.hostServices.messaging.requestMany('hello.world.request.many', payload);