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:
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.
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')
}
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:
(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 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.
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);