1.1.3 • Published 4 years ago

jrfws v1.1.3

Weekly downloads
1
License
MIT
Repository
github
Last release
4 years ago

# jrfws

Deprecated. New version jrf-ws-3

jrfws is a async/await package for creating real-time api, based on websockets. Is a wrapper over easy and fast ws. Can work independently or in conjunction with koa.

jrfwslogo

Installation

$ npm i jrfws --save

jrfws - это async/await пакет для создания api реального времени, на основе websockets. Является оберткой над легким и быстрым ws. Может работать самостоятельно или в связке с koa.

Start server

const JRFWS = require('jrfws');  
const jrfws = new JRFWS();  
  
async function initServer() {

  /// any code	
  
  let opt = {  
  port: 3003  
  };  
  /// default port: 3001  
  await jrfws.startServer(opt);  
}  
  
initServer();

Более подробно про opt сервера можно прочитать из официальной документации ws

Start server with Koa

const Koa = require('koa');  
const JRFWS = require('jrfws');  
const app = new Koa();  
const jrfws = new JRFWS();

/// any code

/// http
jrfws.attach(app);
app.listen(3001);

/// or https
jrfws.attach(app, true, {
  key: fs.readFileSync(...),
  cert: fs.readFileSync(...),
  ca: fs.readFileSync(...)
});
app.listen(3001);

/// jrfws == app.jrfws ---> true

Routing

Добавление routingа должно быть до запуска сервера. Добавление происходит с помощью:

await jrfws.route(route, act, func(data, stop));
paramtyperequireddescription
routestringПуть
actstringДействие относительно пути
funcfunctiontrueАсинхронная функция принимающая: data - данные посланные сообщением, stop - асинхронная функция, вызов которой приостановит последующий routing

data состоит из

paramtypedescription
dataanyДанные любого типа посланные с клиента
routestringПуть посланный с клиента
actstringДействие относительно пути посланное с клиента
clientobjectВнутренний объект клиента ws, которому добавлен метод sendMes(data, route, act) для отправки сообщения ответа клиенту
const JRFWS = require('jrfws');  
const jrfws = new JRFWS();  
  
async function initServer() {  
    
  /// routing before start server  
  /// step 1
  await jrfws.route(async (data, stop) => {  
  /// any code  
  /// for stop next routing: await stop();
    data.steps = 'step1; ';  
    console.log('all route before routing');  
 });  
  /// step 2  
  await jrfws.route('users', async (data, stop) => {  
  /// any code  
  /// for stop next routing: await stop(); 
    data.steps += 'step2; ';  
    console.log('route with route: users or users. or users/');  
 });  
  /// step 3  
  await jrfws.route('users', 'add', async (data, stop) => {  
  /// any code  
  /// for stop next routing: await stop();
    data.steps += 'step3; ';  
    console.log('route with route: user and act: add');  
 });  
  /// step 4  
  await jrfws.route('users.roles', async (data, stop) => {  
  /// any code  
  /// for stop next routing: await stop();
    data.steps += 'step4; ';  
    console.log('route with route: users.roles or users/roles  or users.roles. or users/roles/');  
 });  
  /// step 5  
  await jrfws.route('users.roles', 'add', async (data, stop) => {  
  /// any code  
  /// for stop next routing: await stop();
    data.steps += 'step5; ';  
    console.log('route with route: users.roles or users/roles and act: add');  
 });  
  /// step 6  
  await jrfws.route(async (data, stop) => {  
  /// any code  
  /// for stop next routing: await stop();
    data.steps += 'step6; ';  
    await data.client.sendMes(data.steps);
    console.log('all route after routing');  
 });  
  /// step 7  
  await jrfws.route('not found', async (data, stop) => {  
  /// any code  
  data.steps += 'step7; ';  
  await data.client.sendMes(data.steps);
  console.log('route not found');  
 });  
  /// start server after routing  
  let opt = {  
  port: 3003  
  };  
  /// default port: 3001  
  await jrfws.startServer(opt);  
}  
  
initServer();

Start client

await jrfwsClient.startClient(url, reconnect);
paramtyperequireddescription
urlstringtrueСтрока подключения к серверу
reconnectbooleanПодключаться к серверу автоматически при разрывах. Если параметр не задать, то по умолчанию true
const JRFWS = require('jrfws');  
const jrfwsClient = new JRFWS();  
  
async function initClient() {  
  await jrfwsClient.startClient('ws://localhost:3003');  
}  
  
initClient();

Client тоже поддерживает routing

data состоит из

paramtypedescription
dataanyДанные любого типа посланные с сервера
routestringПуть посланный с сервера
actstringДействие относительно пути посланное с сервера
const JRFWS = require('jrfws');  
const jrfwsClient = new JRFWS();  
  
async function initClient() {  

  /// routing before start client  
  /// step 1  
  await jrfwsClient.route(async (data, stop) => {  
  /// any code  
  /// for stop next routing: await stop();
    console.log('all route before routing');  
 });  
 
  /// start client after routing  
  await jrfwsClient.startClient('ws://localhost:3003');  
}  
  
initClient();

Client имеет события onopen, onerror, onclose, onmessage.

jrfwsClient.onopen = async () => {  
  console.log('open');  
};

Webclient

Webclient может все что и client

<script src="js/webclient.js"></script>
let jrfws;  
  
document.addEventListener('DOMContentLoaded', start());  
  
async function start() {  
  
  jrfws = new JRFWS();  
  await routing();  
  await jrfws.connectToWs('ws://localhost:3003');  
  
}  
  
async function routing() {  
  
  await jrfws.route('users', 'login', async (data, stop) => {  
   if (!data.data.okay || !data.data.user) {  
   console.log('Invalid login');  
   stop();  
   return;  
 }
   await setChatUser(data.data.user);  
 });
 
} 

Send message from client to server

/// Mes with data, route and act
await jrfwsClient.sendMes(data, route, act);

/// Mes with route and act
await jrfwsClient.sendMes(null, route, act);

/// Mes with route
await jrfwsClient.sendMes(null, route);

/// Mes with data
await jrfwsClient.sendMes(data);
paramtypedescription
dataanyДанные любого типа
routestringПуть
actstringДействие относительно пути
async function sendMes() {  
  
  await jrfwsClient.sendMes(null, 'not found path');  
  // step1; step6; step7;  
  
  await jrfwsClient.sendMes('only data');  
  // step1; step6;  
  
  await jrfwsClient.sendMes(null, 'users');  
  // step1; step2; step6;  
  
  await jrfwsClient.sendMes({users: []}, 'users', 'add');  
  // step1; step2; step3; step6;  
  
  await jrfwsClient.sendMes(null, 'users.roles');  
  // step1; step2; step4; step6;  
  
  await jrfwsClient.sendMes(null, 'users/roles');  
  // step1; step2; step4; step6;  
  
  await jrfwsClient.sendMes({role: 'Rick'}, 'users.roles', 'add');  
  // step1; step2; step4; step5; step6;  
  
}

Send message from server to client

/// Mes with data, route and act
await data.client.sendMes(data, route, act);

/// Mes with route and act
await data.client.sendMes(null, route, act);

/// Mes with route
await data.client.sendMes(null, route);

/// Mes with data
await data.client.sendMes(data);
paramtypedescription
dataanyДанные любого типа
routestringПуть
actstringДействие относительно пути
await jrfws.route('not found', async (data, stop) => {  
  /// any code  
  data.steps += 'step7; ';  
  await data.client.sendMes(data.steps);  
  console.log('route not found');  
});

Broadcast

All clients

jrfws.wss.clients /// array ws clients

Add group

await jrfws.addGroup(nameGroup);
paramtypedescription
nameGroupstringИмя группы, кроме all

Del group

await jrfws.delGroup(nameGroup);
paramtypedescription
nameGroupstringИмя группы, кроме all

Add client to group

await jrfws.addClientToGroup(nameGroup, client);
paramtypedescription
nameGroupstringИмя группы
clientobjectclient type ws data.client

Del client from group

await jrfws.delClientFromGroup(nameGroup, client);
paramtypedescription
nameGroupstringИмя группы
clientobjectclient type ws data.client

Broadcast

await jrfws.broadcast(nameGroup, data, route, act);
paramtypedescription
nameGroupstringИмя группы. 'all' для всех jrfws.wss.clients
dataanyДанные любого типа
routestringПуть
actstringДействие относительно пути

Broadcast except client(s)

await jrfws.broadcastExcept(nameGroup, except, data, route, act);
paramtypedescription
nameGroupstringИмя группы. 'all' для всех jrfws.wss.clients
exceptobject or arrayclient(s) type ws data.client
dataanyДанные любого типа
routestringПуть
actstringДействие относительно пути

Get routes

Получить все routes с acts

let routes = await jrfws.getRoutes();

routes = [
            {
                route: 'users',
                acts: [
                    'add'
                ]
            },
            {
                route: 'users.roles',
                acts: [
                    'add'
                ]
            }
        ];

Example

Simplechat is an example of using packages of jrfws and jrfdb (odm mongodb).

chat

1.1.3

4 years ago

1.1.2

4 years ago

1.1.1

5 years ago

1.1.0

6 years ago

1.0.5

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago