Host Services in JavaScript Functions

The JavaScript functions that Nex executes are run inside a V8 sandbox, which is often also contained within a Firecracker sandbox. As a result, these JavaScript functions don’t have the same kind of freedom of access to capabilities that other function types (e.g. Node.js in a cloud provider). However, we’ve made the most common use cases available by default through host services.

Host services aren’t just access to arbitrary capabilities, they’re access to managed capabilities that are designed to be pre-provisioned and ready to go, so function developers don’t have to write provisiong code, they can focus solely on the capability abstractions they need.

HTTP Client

If you want to make HTTP calls from your function, you can do so with the HTTP client:

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

All of the HTTP methods are supported as functions:

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

Key-Value Store

Every Nex-managed JavaScript function has access to an abstraction over a key-value store, which is internally backed by a NATS Key-Value bucket.

  1. this.hostServices.kv.set('hello', payload);
  2. this.hostServices.kv.delete('hello');
  3. this.hostServices.kv.set('hello2', payload);
  4. return {
  5. keys: this.hostServices.kv.keys(),
  6. hello2: this.hostServices.kv.get('hello2')
  7. }

Again, note that you don’t have to manually or explicitly provision the bucket. You can assume that your function has its own, isolated bucket and that it is safe in a multi-tenant environment.

Object Store

Every Nex-managed function has access to a managed object store. The following code shows how JavaScript can interact with this store:

  1. (subject, payload) => {
  2. this.hostServices.objectStore.put('hello', payload);
  3. this.hostServices.objectStore.delete('hello');
  4. this.hostServices.objectStore.put('hello2', payload);
  5. return {
  6. list: this.hostServices.objectStore.list(),
  7. hello2: String.fromCharCode(...this.hostServices.objectStore.get('hello2'))
  8. }
  9. };

Core Messaging

JavaScript functions receive messages on their trigger subjects, which are specified at deployment time. To publish or make requests, host services provides access to a core NATS black box.

  1. this.hostServices.messaging.publish('hello.world', payload);
  2. req = this.hostServices.messaging.request('hello.world.request', payload);
  3. reqMany = this.hostServices.messaging.requestMany('hello.world.request.many', payload);