NATS Microservice Library
A convenient microservice library based on NATS and compatible with nats-go microservices
Description
This is a typescript-first library that provides a convinient (in 10 lines of code or less!) way to write microservises with out of the box auto discovery, observability and load balancing.
Full interoperability with to-be-released nastcli v0.0.36
that adds nats micro info
, nats micro stats
and nats micro ping
commands
It also supports service schema discovery which is not (yet?) supported by nats micro
Limitations / TODO
- No multi-reply support yet.
When you send a message you will be getting exactly one response (or a timeout error)
- No load balancing yet
Usage
It is extremely simple:
Functional way
const broker = await new Broker('echo' + process.pid).connect();
await Microservice.create(
broker,
{
name: 'echo',
description: 'Simple echo microservice',
version: '0.0.1',
methods: {
say: {
handler: (text) => text,
},
'config-change-event': {
handler: console.log,
subject: '$EVT.config.change',
},
},
}
);
Declarative way
class EchoMicroservice {
public get config(): MicroserviceConfig {
return {
name: 'echo',
description: 'Simple echo microservice',
version: '0.0.1',
methods: {
say: { handler: this.say },
'config-change-event': { handler: this.onConfigChange },
},
};
}
private say(text: string): string {
return text;
}
private onConfigChange(change: unknown): void {
console.log(change);
}
}
const echoMicroservice = new EchoMicroservice();
const broker = await new Broker('echo' + process.pid).connect();
await Microservice.create(broker, echoMicroservice.config);
Using decorators
@microservice({ name: 'echo', description: 'Decorated service' })
export default class EchoMicroservice {
@method({name: 'say'})
private reply(text: string): string {
return text;
}
@method({ subject: '$EVT.config.change' })
private configChangeEvent(change: unknown): void {
console.log(change);
}
}
const echoMicroservice = new EchoMicroservice();
const broker = await new Broker('echo' + process.pid).connect();
await Microservice.createFromClass(broker, echoMicroservice);