1.1.1 • Published 5 years ago

ms-udp v1.1.1

Weekly downloads
17
License
Apache-2.0
Repository
github
Last release
5 years ago

ms-udp

Solution for communication between services using UDP protocol with built-in auto-retry & round-robin balancing. 🔬

Install

$ npm i ms-udp -S

Examples

There are some simple examples.

API

Server

.constructor()

const server = new udp.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 udp.Client({
  services: {
    balances: '127.0.0.1:3000',
  },
});

.mock(requests)

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)

This method asks other service for something.

app.use(async (ctx, next) => {
  const isAuth = await ctx.udp.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 { Client } = require('ms-udp');

const app = new Koa();
const client = new Client();

app.use(client.middleware());

app.use((ctx) => {
  ctx.body = 'Hello, world!';
});

app.listen(3000);
1.1.1

5 years ago

1.1.0

5 years ago

1.0.0-rc.0

5 years ago

0.3.6

5 years ago

0.3.5

5 years ago

0.3.4

5 years ago

0.3.3

5 years ago

0.3.2

5 years ago

0.3.1

5 years ago

0.3.0

5 years ago

0.2.1

5 years ago

0.2.0

5 years ago

0.1.2

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago

0.0.1

5 years ago