Giter Site home page Giter Site logo

alexkander / loopback-socket Goto Github PK

View Code? Open in Web Editor NEW
6.0 1.0 2.0 596 KB

Loopback module for create Socket.io connections and allow call methods and make subscriptions

License: MIT License

JavaScript 100.00%
loopback socket subscription strongloop security auth io realtime websocket events express expressjs

loopback-socket's Introduction

loopback-socket

npm version Build Status Coverage Status

Loopback module for create Socket.io connections and allow call methods.

Installation

npm install loopback-socket --save

Usage

Server side

Include

const LoopbackSocket = require('loopback-socket');

LoopbackSocket.get(name, [timeout])

Create or get a instance with a specific name.

Arguments
Name Type Description
name string Name to instance. Required
[timeout] integer Time to wait authentication after establish connection before disconnect the socket. Optional.
Example
const loopbackSocket = LoopbackSocket.get('name');
const loopbackSocket = LoopbackSocket.get('name', 2000);

loopbackSocket.start(io)

Configure authentication, callbacks and methods with a server socket.

Arguments
Name Type Description
io object Server Socket IO instance. Required.
Example
const server = require('http').createServer();
const io = require('socket.io')(server);
loopbackSocket.start(io);

loopbackSocket.auth(authentication)

Set the function to authenticate connected sockets.

Arguments
Name Type Description
authentication autentication function or object Function called with (socket, credentials, [cb]) arguments or object like { model: Model, method: methodName } where Model is a class and methodName is one of its methods (defined or to be defined) like autentication function.
Authentication function

If an error is thrown in this function or it return a false value then authentication fails. If argument cb is not defined then the returned value will be a the authentication response, and if this value is a promise, then it will be resolved before.

Name Type Description
socket object Socket connected. Required.
credentials object Credentials received. Required.
[cb] function Callback with (err, success) arguments to async return value with NodeJs callback style. Optional.
Example
// Authentication function with NodeJs callback style
function customAuthentication(socket, credentials, cb) {
  User.getUserByCredentials(credentials, cb);
}

// Authentication function with direct value returned o Promise style
function customAuthentication(socket, credentials) {
  return User.getUserByCredentials(credentials); // return data or a promise
}

// Direct setting
loopbackSocket.auth(customAuthentication);

// Setting through a Model
function MyModel() {};

loopbackSocket.auth({
  model: MyModel,
  method: 'customAuthentication'
});

MyModel.customAuthentication = authentication;

loopbackSocket.onConnected(handler)

Add a on connected handler.

Arguments
Name Type Description
handler handler function or object Function called with (socket, credentials, [cb]) arguments or object like { model: Model, method: methodName } where Model is a class and methodName is one of its methods (defined or to be defined) with like handler function.
Handler function

If argument cb is not defined then the returned value will be a the handler response, and if this value is a promise, then it will be resolved before.

Name Type Description
socket object Socket connected. Required.
credentials object Credentials received. Required.
[cb] function Callback with (err, success) arguments to async return value with NodeJs callback style. Optional.
Example
// Authentication function with NodeJs callback style
function customOnConnectedHandler(socket, credentials, cb) {
  User.getUserByCredentials(credentials, cb);
}

// Authentication function with direct value returned o Promise style
function customOnConnectedHandler(socket, credentials) {
  return User.getUserByCredentials(credentials); // return data or a promise
}

// Direct adding
loopbackSocket.onConnected(customOnConnectedHandler);

// Adding through a Model
function MyModel() {};

loopbackSocket.onConnected({
  model: MyModel,
  method: 'customOnConnectedHandler'
});

MyModel.customOnConnectedHandler = customOnConnectedHandler;

loopbackSocket.removeOnConnected(handler)

Remove a connected handler

Arguments
Name Type Description
handler function or object Function called with (socket, credentials, [cb]) arguments or object like { model: Model, method: methodName } where Model is a class and methodName is one of its methods (defined or to be defined) with like handler function.
Example
// Direct remove
loopbackSocket.onConnected(customOnConnectedHandler);

// Remove Model method
function MyModel() {};

loopbackSocket.removeOnConnected({
  model: MyModel,
  method: 'customOnConnectedHandler'
});

loopbackSocket.defineMethod(methodName, method)

Define a method to call by socket connection or replace one existing.

Arguments
Name Type Description
methodName string Method name.
method method function or object Function called with (socket, credentials, args, [cb]) arguments or object like { model: Model, method: methodName } where Model is a class and methodName is one of its methods (defined or to be defined) with like method function.
Method function

If argument cb is not defined then the returned value will be the method called reponse, and if this value is a promise, then it will be resolved before.

Name Type Description
socket object Socket connected. Required.
credentials object Credentials received. Required.
args. object Arguments to call method. Required.
[cb] function Callback with (err, success) arguments to async return value with NodeJs callback style. Optional.
Example
/// Method function with NodeJs callback style
function customMethod(socket, credentials, args, cb) {
  let data;

  // Option 1
  cb(null, data); // Client receives { result: data }
  
  // Option 2
  cb('myError');  // Client receives { error: 'myError' }

}

/// Method function with direct value returned o Promise style
function customMethod(socket, credentials, args) {
  let dataOrPromise;

  // Option 1
  return dataOrPromise; // Client receives { result: dataOrPromiseResolvedValue }

  // Option 2
  throw 'myError'; // Client receives { error: 'myError' }

}

// Direct definition
loopbackSocket.defineMethod('customMethod', customMethod);


// Definition through a Model
function MyModel() {};

loopbackSocket.defineMethod('customMethod', {
  model: MyModel,
  method: 'customMethod',
});

MyModel.customMethod = customMethod;

loopbackSocket.removeMethod(methodName)

Remove a method of socket.

Arguments
Name Type Description
methodName string Method name to remove.
Example
// Direct remove
loopbackSocket.onConnected('customMethod');

Client side sample

const socket = io('http://localhost');

socket.on('connect', (socket) => {
  // send credentials
  socket.emit('authentication', credentials);
});

socket.on('authenticated', (socket) => {
  // socket authenticated
});

socket.on('unauthorized', (socket) => {
  // socket failed authentication
});

function callMyMethod() {
  // Call a defined socket method
  socket.emit('myMethod', {}, (response) => {
    if (response.error) {
      // Method return a error;
      return;
    }
    // Method success;
    console.log(response.result);
  });
}

Samples

Loopback + AngularJS:

https://github.com/arondn2/loopback-socket/tree/master/examples/loopback

Troubles

If you have any kind of trouble with it, just let me now by raising an issue on the GitHub issue tracker here:

https://github.com/arondn2/loopback-socket/issues

Also, you can report the orthographic errors in the READMEs files or comments. Sorry for that, I do not speak English.

Tests

npm test or npm run cover

Contributing

In lieu of a formal style guide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code.

loopback-socket's People

Contributors

alexkander avatar dependabot[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

ebarahona teorich

loopback-socket's Issues

vulnerabilities when installing loopback-socket

Here is audit output

matejs-MacBook-Pro:socket-example matejsimunic$ npm audit
                                                                                
                       === npm audit security report ===                        
                                                                                
# Run  npm install [email protected]  to resolve 9 vulnerabilities
SEMVER WARNING: Recommended action is a potentially breaking change
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Low           │ Regular Expression Denial of Service                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ debug                                                        │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ loopback-socket                                              │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ loopback-socket > socketio > socket.io > debug               │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/534                       │
└───────────────┴──────────────────────────────────────────────────────────────┘


┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Low           │ Regular Expression Denial of Service                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ debug                                                        │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ loopback-socket                                              │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ loopback-socket > socketio > socket.io > engine.io > debug   │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/534                       │
└───────────────┴──────────────────────────────────────────────────────────────┘


┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Low           │ Regular Expression Denial of Service                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ debug                                                        │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ loopback-socket                                              │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ loopback-socket > socketio > socket.io > socket.io-adapter > │
│               │ debug                                                        │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/534                       │
└───────────────┴──────────────────────────────────────────────────────────────┘


┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Low           │ Regular Expression Denial of Service                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ debug                                                        │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ loopback-socket                                              │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ loopback-socket > socketio > socket.io > socket.io-client >  │
│               │ debug                                                        │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/534                       │
└───────────────┴──────────────────────────────────────────────────────────────┘


┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Low           │ Regular Expression Denial of Service                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ debug                                                        │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ loopback-socket                                              │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ loopback-socket > socketio > socket.io > socket.io-client >  │
│               │ engine.io-client > debug                                     │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/534                       │
└───────────────┴──────────────────────────────────────────────────────────────┘


┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Low           │ Regular Expression Denial of Service                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ debug                                                        │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ loopback-socket                                              │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ loopback-socket > socketio > socket.io > socket.io-adapter > │
│               │ socket.io-parser > debug                                     │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/534                       │
└───────────────┴──────────────────────────────────────────────────────────────┘


┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Low           │ Regular Expression Denial of Service                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ debug                                                        │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ loopback-socket                                              │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ loopback-socket > socketio > socket.io > socket.io-client >  │
│               │ socket.io-parser > debug                                     │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/534                       │
└───────────────┴──────────────────────────────────────────────────────────────┘


┌───────────────┬──────────────────────────────────────────────────────────────┐
│ Low           │ Regular Expression Denial of Service                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ debug                                                        │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ loopback-socket                                              │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ loopback-socket > socketio > socket.io > socket.io-parser >  │
│               │ debug                                                        │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/534                       │
└───────────────┴──────────────────────────────────────────────────────────────┘


┌───────────────┬──────────────────────────────────────────────────────────────┐
│ High          │ Regular Expression Denial of Service                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ parsejson                                                    │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ loopback-socket                                              │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ loopback-socket > socketio > socket.io > socket.io-client >  │
│               │ engine.io-client > parsejson                                 │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://nodesecurity.io/advisories/528                       │
└───────────────┴──────────────────────────────────────────────────────────────┘


found 9 vulnerabilities (8 low, 1 high) in 2543 scanned packages
  9 vulnerabilities require semver-major dependency updates.

Apply hooks before main-method called

Hi

Is there any way that hook method to be executed before calling, Just like API-calls.
I've added validations in beforeRemote method. Before/After or any other hook contains params ctx, unused, next..

Is there a way to achieve it.

Thanks in advance.

Is this still a package to use ?

Hi,

Since this package's here for a while, I wanted to know if it still a good thing to use it, or follow the Loopback 3 tutorial about socket.io.

Thanks !

Promise rejection

Sup!

I ran into a problem with custom handlers:

  function addUser(socket, credentials, args, cb) {
    socket.join(args.eventId);
    socket.username = args.username;
    socket.userId = args.userId;
    socket.eventId = args.eventId;
    let user = app.models.JoinallyUser.findById(args.userId, {
      fields: {
        firstname: true,
        birthdate: true,
        pictureId: true,
        sex: true,
      },
    }).then((user) => {
      onlineUsers['args.userId'] = user;
    });
    debug('User ' + args.username + ' joined Eventroom with ID ' +
      args.eventId);
    ++numUsers;

    socket.emit('login', {
      numUsers: numUsers,
    });
    socket.to(args.eventId).emit('user joined', {
      username: args.username,
      numUsers: numUsers,
    });
    cb(null, true);
  }

[...]
  socket.defineMethod('add user', addUser);

Error Log:

(node:26029) UnhandledPromiseRejectionWarning: TypeError: done is not a function
at Promise.resolve.then.then.catch.then (/root/devBetaBackend/node_modules/loopback-socket/lib/loopback-socket.js:52:7)
at
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:26029) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:26029) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Any idea what I could be doing wrong? :)

Thanks,

Marvin / Nop0x

LoopbackSocket.get is not a function

Hello, I am running your sample and im confused on what should I "get" on the "LoopbackSocket.get" function. What is "myapp" in this instance?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.