Skip to content

bifot/ms-tcp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ms-tcp

Solution for communication between services using TCP protocol with built-in auto-retry & reconnect. 🔬

Install

$ npm i ms-tcp -S

Tests

$ npm test

Examples

There are some simple examples.

API

Server

.constructor()

const server = new tcp.Server();

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

.use(...middlewares)

This method creates common middlewares.

.listen(port[, host, callback])

This method starts listening.

Client

.constructor(options)

const client = new tcp.Client({
  services: {
    balances: '127.0.0.1:3000',
  },
});

.mock(requests)

  • requests <Object>
    • [key] <string> Service name
    • [value] <Object> Service requests
      • [key] <string> Event name
      • [value] <any> Event response

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

.ask(name[, payload, options])

  • event <string> Event name in format <service_name>.<action>
  • data <?Object> Event data
  • options <?Object> Options
    • attempts <?number> Maximum number of attempts (default: 5)
    • timeout <?number> Maximum timeout in ms (default: 5000)

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

.middleware()

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);

About

Solution for communication between services using TCP protocol with built-in auto-retry & reconnect. 🔬

Resources

License

Stars

Watchers

Forks

Packages

No packages published