Solution for communication between services using TCP protocol with built-in auto-retry & reconnect. 🔬
$ npm i ms-tcp -S
$ npm test
There are some simple examples.
const server = new tcp.Server();
event
<string> Action name...middlewares
<function[]> Action middlewares
This method creates action.
const { Balances } = require('./db');
server.on('get', async (ctx) => {
const { amount } = await Balances.findOne({
userId: ctx.payload.userId,
});
ctx.reply(amount);
});
...middlewares
<function[]> Common middlewares
This method creates common middlewares.
This method starts listening.
options
<Object>services
<Object> Available services[key]
- <string> Service name[value]
- <string / Array<string> / Object{host, port} / Array<Object{host, port}>> Service's address
const client = new tcp.Client({
services: {
balances: '127.0.0.1:3000',
},
});
requests
<Object>
This method save mocks responses for .ask
.
if (process.env.NODE_ENV === 'test') {
client.mock({
balances: {
get: 200,
},
users: {
create: payload => payload.userId >= 100,
},
});
}
const [balance, badUser, goodUser] = await Promise.all([
client.ask('balances.get', { userId: 1 }),
client.ask('users.create', { userId: 10 }),
client.ask('users.create', { userId: 200 }),
]);
console.log(balance); // => 200
console.log(badUser); // => false
console.log(goodUser); // => true
event
<string> Event name in format<service_name>.<action>
data
<?Object> Event dataoptions
<?Object> Options
This method asks other service for something.
app.use(async (ctx, next) => {
const isAuth = await ctx.tcp.ask('users.checkAuth', {
login: ctx.query.login,
password: ctx.query.password,
});
ctx.assert(isAuth, 403);
await next();
});
This method returns middleware for Koa or Express.
const Koa = require('koa');
const tcp = require('tcp');
const app = new Koa();
const client = new tcp.Client();
app.use(client.middleware());
app.use((ctx) => {
ctx.body = 'Hello, world!';
});
app.listen(3000);