Coder Social home page Coder Social logo

rf-api-websocket's Introduction

rf-api-websocket

rf-api implementation for RPC over websockets using JSON messages with optional ACL.

ws server

  • Uses express server instance
  • Websocket communication service
  • Allows safe RPC
  • Uses JSON messages

ws methods

addHandler

Add a simple callback handler. Errors can be signalled via exceptions Any previous handler with the same func name will be replaced.

services.addHandler (funcName, callback, acl = {})
  • funcName The name of the handler. In order for the handler to be called, this needs to be used in the func attribute of the received websocket message.
  • callback The handler function(msg, responseCallback(msg))
  • acl Optional ACD configuraton

addPromiseHandler

Add a promise callback handler that either resolves to null (no response) or to response data and signals exceptions via rejection (logged, no response. Any previous handler with the same func name will be replaced.

services.addPromiseHandler (funcName, genPromise, acl = {})
  • funcName The name of the handler. In order for the handler to be called, this needs to be used in the func attribute of the received websocket message.
  • callback The handler function(msg, responseCallback(msg))
  • acl Optional ACD configuraton

sendObj

services.sendObj (ws, obj)

TODO: integrate callbackID maybe one raw send method, and one preconfigured (default to use)

broadcast

Send the given object to ALL the currently connected websockets NOTE: This sends the object as-is.

services.broadcast (obj)

Getting started

start the package

When the module is started, the websocket server and handler is automatically registered against the HTTP server. You dont need to start the server manually!

// prepare backend
var config = require('rf-config').init(__dirname); // config
var http = require('rf-http').start({ // webserver
   pathsWebserver: config.paths.webserver,
   port: config.port
});
var API = require('rf-api').start({app: http.app}); // prepare api
var mongooseMulti = require('mongoose-multi'); // databases
var db = mongooseMulti.start(config.db.urls, config.paths.schemas);


db.global.mongooseConnection.once('open', function () {

   // optional: start access control; has to be done before starting the websocket
   require('rf-acl').start({
      API: API,
      db: db,
      app: http.app,
      sessionSecret: dbSettings.sessionSecret.value
   });

   // start websocket connection;
   require('rf-api-websocket').start({API: API, http: http});

   // start requests
   API.startApiFiles(config.paths.apis, function (startApi) {
      startApi(db, API, services);
   });
});

Use Websocket requests

Websocket messages have the form: {func: "", data: {...}, token: ""} Any other attributes are copied to the response

Register a handler like this:

API.onWSMessage("myfunc", (msg, respondWS, userInfo) => {
    // userInfo contains the object extracted from the JWT (or {} if no token was supplied)
    // If the user does not have the required permissions or the message is malformed,
    // this function is not called but instead an error msg is sent!
    if(!userInfo.isAdmin) {
      return false;
    }
    // Handle message (msg is .data of the original message)
    console.log(msg.foobar)
    // Then send response. Convention is to have an err attribute
    respondWS({err: null, info: "It works"});
    // NOTE: You can call respondWS multiple times if required!
}, {}) // Empty ACL => no auth required

See the rf-acl package for documentation about the ACL syntax

If you are using Promises, use this syntax

API.onWSMessagePromise("myfunc", (msg, respondWS, userInfo) => {
  return new Promise((resolve, reject) => {
    if(!userInfo.isAdmin) {
      return reject("nope"); // Will send {err: "nope"}
    }
    return resolve({"foo": "bar"}); // will send {err: null, "foo": "bar"}
  });
}, {}) // Empty ACL => no auth required

Development

Install the dev tools with

npm install

Then you can runs some test cases and eslint with:

npm test

Generate Docs:

npm run-script doc

To Do

  • get the everything running

Legal Issues

  • License: MIT
  • Author: Rapidfacture GmbH

rf-api-websocket's People

Contributors

ulikoehler avatar felixfurtmayr avatar rf-alex avatar

Watchers

 avatar James Cloos avatar Marc Itzenthaler avatar Regina Galambos avatar  avatar

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.