@egodigital/microservices
Shared library for microservices, written for Node.js, in TypeScript.
Install
Execute the following command from your project folder, where your package.json
file is stored:
npm install --save @egodigital/microservices
Usage
Auth
Passwords
Hash passwords with bcrypt:
import { checkPassword, checkPasswordSync, hashPassword, hashPasswordSync } from '@egodigital/microservices';
const hash1 = await hashPassword('test');
const matches2 = await checkPassword('test', hash1);
const hash2 = hashPasswordSync('test');
const matches2 = checkPasswordSync('test', hash2);
JWT
Sign and verify JSON Web Tokens:
import { signJWT, verifyJWT } from '@egodigital/microservices';
interface IUserToken {
uuid: string;
}
const jwt = signJWT({
uuid: 'cb246b52-b8cd-4916-bfad-6bfc43845597'
});
const decodedToken = verifyJWT<IUserToken>(jwt);
Express
Use predefined Express middleware to verify and decode JWTs:
import express from 'express';
import { withJWT } from '@egodigital/microservices';
const app = express();
app.get('/', withJWT(), async (request, response) => {
});
app.listen(4242, () => {
console.log('Service is listening ...');
});
Constants
Name | Description | Example |
---|
BCRYPT_ROUNDS | The number of rounds for bcrypt hashing. Default: 10 | 12 |
JWT_SECRET | The secret for signing and validating JWT. | mySecretJWTSecret |
NATS_CLUSTER_ID | The name of the cluster, that contains all microservices. | my-cluster |
NATS_GROUP | The name of the pod group / Kubernetes deployment. | my-service-or-deployment |
NATS_URL | The URL to the NATS server. | http://my-nats-service:4222 |
POD_NAME | The name of the pod. This should come as imported metadata from Kubernetes. | my-service-or-deployment-xcsgbxv |
NATS
Connect to a NATS server:
import { stan } from '@egodigital/microservices';
await stan.connect();
stan.exitOnClose();
Listener
Listen for events:
import { NatsListener } from '@egodigital/microservices';
interface IMyEvent {
foo: string;
bar: number;
}
const myEventListener = new NatsListener<IMyEvent>('my.event');
myEventListener.onMessage = async (context) => {
};
myEventListener.listen();
Publisher
Publish events:
import { NatsPublisher } from '@egodigital/microservices';
interface IMyEvent {
foo: string;
bar: number;
}
const myEventPublisher = new NatsPublisher<IMyEvent>('my.event');
await myEventPublisher.publish({
foo: "TM+MK",
bar: 42
});
Documentation
The API documentation can be found here.