Giter Site home page Giter Site logo

spacebro-client's Introduction

spacebro client

🌟 Connect easily to a spacebro server.

js-standard-style node node node

🌍 Installation

yarn add spacebro-client
# or
npm i -S spacebro-client

πŸ‘‹ Usage

First, you need to start a spacebro server.

$ npm i -g spacebro # or yarn global add spacebro
$ spacebro

Then, write the following client code:

const { SpacebroClient } = require('spacebro-client')

const client = new SpacebroClient({
  host: '127.0.0.1',
  port: 36000,
  channelName: 'bar',
  client: {
    name: 'foo',
    description: "a foo tool",
    in: {
      inFoo: {
        eventName: "inFoo",
        description: "Input foo",
        type: "all"
      }
    },
    out: {
      outBar: {
        eventName: "outBar",
        description: "Output bar",
        type: "all"
      }
    }
  },
  connection: "bar/outBar => bar/inFoo"
})

client.on('inFoo', (data) => console.log('inFoo', data))
client.emit('outBar', { do: stuff})

The connection string was sent to the spacebro server, that will then connects every event named outBar from client bar to a new event named inFoo sent to client bar

πŸš€ API

class SpacebroClient([options], [connect])

Look for a server, and return a handle to the connection.

// For more details about possible options, see below.
const client = new SpacebroClient({
  host: '127.0.0.1',
  port: 8888,
  client: {name: 'foo'},
  channelName: 'bar'
})

options:

name default required Β description
host - required The spacebro server's address. Ignored if connect is false.
port - required The spacebro server's address. Ignored if connect is false.
client.name null recommended Your client's name. Can be useful to perform targeted events and for monitoring.
channelName null recommended The channel your app will communicate in. This is especially usefull if you have multiple apps using the same server.
verbose true optional Should spacebro-client display logs (connection / emission / reception)?
sendBack true optional Should this client receive the events it sent?

connect

If the connect parameter is false, then the options are saved and a disconnected handle is returned; you have to call its connect method later before you can emit or receive events.

Default value: true

const client = new SpacebroClient({
  client: {name: 'myClient'},
  channelName: 'someChannel'
}, false)

// ...

client.connect('127.0.0.1', 8888)

create([options])

Look for a server, and creates a handle to the connection. Takes the same options as new SpacebroClient. Returns a Promise like client.connect.

setDefaultSettings(options, [verbose])

Overwrite the default options of new SpacebroClient with the given options.

If standard-settings is installed in your module, spacebro-client will call this function with the contents of services.spacebro from your settings file.

client.connect(address, port)

Look for a server, and connect client to this server. Returns a Promise that resolves to client when the connection is established, or throws an error if the connection fails.

client.emit(eventName[, data])

Broadcast a specific event to all the clients in the channel. data must be a JSON object.

client.sendTo(eventName, target[, data])

Send an event to a specific target in the channel. data must be a JSON object.

client.on(eventName, handler)

Listen to a specific event.

client.once(eventName, handler)

Listen to a specific event only once.

client.off(eventName)

Remove a specific event listener.

client.disconnect()

Close the connection.

Socket.io callbacks (acknowledgments)

Spacebro now works with acknowlegdments too !

const { SpacebroClient } = require('spacebro-client')

const client = new SpacebroClient({
  host: '127.0.0.1',
  port: 36000,
  channelName: 'bar',
  client: {
    name: 'foo',
    description: "a foo tool",
    in: {
      inFoo: {
        eventName: "inFoo",
        description: "Input foo",
        type: "all"
      }
    },
    out: {
      outBar: {
        eventName: "outBar",
        description: "Output bar",
        type: "all"
      }
    }
  },
  connection: "bar/outBar => bar/inFoo"
})

client.on('inFoo', (data, fn) => {
  console.log('inFoo', data)
  fn('thank you')
})

client.emit('outBar', { do: stuff}, function (data) {
  console.log('Received from callback: ' + data)
})

πŸ–₯ Browser

You can use spacebro-client in the browser. You will need the following dependencies:

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.0/socket.io.js"></script>
<script src="https://wzrd.in/standalone/socketio-wildcard@latest"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-signals/1.0.0/js-signals.min.js"></script>

After adding these dependencies, you can include the spacebro-client lib like any script:

<script src="./dist/spacebro-client.js"></script>

Then use the window.spacebroClient object.

βš› Electron

Spacebro-client also works in Electron. You just require('spacebro-client') in your electron main process and use ipc or web-contents to forward events to the renderer process.

From the example/electron/ folder of this repository:

// In the main process.
const { app, BrowserWindow } = require('electron')
const { SpacebroClient } = require('../../dist/spacebro-client')

let win = null

const client = new SpacebroClient({
  host: '127.0.0.1',
  port: 8888,
  client: {name: 'foo'},
  channelName: 'bar'
})

app.on('ready', () => {
  win = new BrowserWindow({ width: 800, height: 600 })
  win.loadURL(`file://${__dirname}/index.html`)

  for (const eventName of ['hello', 'world']) {
    client.on(eventName, (data) => {
      win.webContents.send(eventName, data)
    })
  }

  win.webContents.on('did-finish-load', () => {
    setTimeout(() => { client.emit('hello', { hello: 'world' }) }, 3000)
    setTimeout(() => { client.emit('world', { world: 'hello' }) }, 5000)
  })
})
<!-- index.html -->
<html>
<body>
  <script>
    require('electron').ipcRenderer.on('hello', (event, message) => {
      console.log(message)
    })
    require('electron').ipcRenderer.on('world', (event, message) => {
      console.log(message)
    })
  </script>
</body>
</html>

Examples

You can find many real life examples in the example/ folder of this repository.

πŸ•³ Troubleshooting

newClient event πŸ‘‹

The Spacebro server automatically broadcasts a newClient event when a client connects. Thus, you should avoid using that event name. See the example/simple-node script for more details.

Using native modules in Electron πŸŒ€

If you want to use spacebro-client in an Electron app, you'll have to use electron-rebuild in order to rebuild MDNS according to the version of Node.js embedded with Electron.

Use the following commands:

$ npm i --save-dev electron-rebuild # or yarn
$ ./node_modules/.bin/electron-rebuild # call the executable every time you add a new native module

You can also add "rebuild": "./node_modules/.bin/electron-rebuild" to your package.json and run npm run rebuild for convenience.

source

yarn and node-gyp issue (i.e not compiling) πŸ€–

You need to use at least yarn version 0.17.8. You might have similar problems with outdated versions of npm, simply try to update it.

source

https

If the spacebro server is on https, use following settings:

  'service': {
    'spacebro': {
      'host': 'https://example.com'
      'port': 0
    }
  }

subdir on server

If the server url is something like https://example.com/subdir. You can use this url as host. Spacebro will process subdir as a path, contrary to socket.io that would process subdir as a namespace.

That means the requested urls will look like https://example.com/subdir/?EIO=3&transport=polling&sid=<id>

ping pong πŸ“

Do not try to test with 'ping' and 'pong' events, those are reserved.

- `ping`. Fired when a ping packet is written out to the server.
- `pong`. Fired when a pong is received from the server.

source

❀️ Contribute

Please follow Standard JS conventions.

The package has lint testing and unit testing baked-in. Please use npm run test to run both sets of tests before making a pull request. Use npm run build to transpile the project.

The project's release versions are named after stars in Andromeda . The current version is named Sirrah.

Enjoy !

spacebro-client's People

Contributors

brendaoud avatar dduvacher avatar emmanuelgeoffray avatar gabrielstuff avatar hugohil avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

spacebro-client's Issues

spacebro-client doesn't work in browser

When loading spacebro-client in my browser using these tags:

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
<script src="https://wzrd.in/standalone/socketio-wildcard@latest"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-signals/1.0.0/js-signals.min.js"></script>
<script type="text/javascript" src="./spacebro-client.js"></script>

I get this error

Uncaught TypeError: Cannot read property 'rst' of undefined
    at Object.<anonymous> (autoconnect.js:10)
    at Object.module.exports (spacebro-client.js:3801)
    at __webpack_require__ (bootstrap c43efc3…:19)
    at Object.<anonymous> (spacebro-client.js:7)
    at Object.<anonymous> (spacebro-client.js:395)
    at __webpack_require__ (bootstrap c43efc3…:19)
    at Object.defineProperty.value (bootstrap c43efc3…:39)
    at bootstrap c43efc3…:39
    at webpackUniversalModuleDefinition (universalModuleDefinition:9)
    at universalModuleDefinition:10

This is due to a require on mdns which should not be imported whem running spacebro-client in a browser. @hugohil @gabrielstuff

Built-in socket.io events should be forwarded

spacebro-client should give some feedback when built-in socket.io events occurs.

Example: if the socket.io connect event is forwarded, the user could listen to the connect event to know when the spacebro-client instance is ready.

spacebroClient.on('connect', function() {
  console.log('spacebroClient ready !')
})

Add custom protocol for connect

Connection option should include : ws://, wss:// or https
Normally it should check for a protocol in the string and append one if none are present

Browser compatibility is broken due to standard-settings

While trying to use spacebro-client directly into a web app, error are thrown complaining about nconf and fs module.

Needed to set: noParse: /standard-settings/

module: {
    noParse:  /standard-settings/,
    rules: [...]

in order to build correctly

Improve tutorial

The tutorial should reflect the new pinger / ponger and more generally the whole API.

Improve docs

Currently the docs is based on the previous version of spacebro. The folder should be update with newly API.

Why altered exist ?

Sometime data can be altered. The question is why.

[  "create",
  {
    data: "match",
    altered: true,
    _to: null,
    _from: "client-em"
  },
  {
    teamA: ["@frederic", "@jean"],
    teamB: ["@pasl", "@jack"],
    status: "new"
  },
  {
  },
  [Function]]

Zeroconf should be more pluggable and use platform specific constraints

Currently the autoconnect.js is based on the library node_mdns.

We aim at supporting several devices and environment in JS :

  • Windows
  • Linux (x64 and ARM)
  • OSX
  • Android
  • iOS

The node_mdns covers Windows, Linux and OSX. It is not the case for Mobile operating system such as iOS and Android.

I've listed here some plugin we might try :

Sends the message twice after disconnect

I have seen this issue many times but I can't reproduce it.
I know for sure we have it when the server reboots and the app in browser is still there
I have tried to reproduce this bug without success with those scenarios:

  • close and start spacebro
  • kill spacebro and start
  • kill -9 spacebro and start
  • disconnect from wifi and reconnect.

I check spacebro logs and I still have only one message sent (no duplicates) after thos operations.
We need to find a scenario to reproduce the issue.

Allow connection object to take unamed client by default

Instead of:

"connection": [
        "spacebro-client/users::find => score-api/users::find",
        "score-api/users updated => spacebro-client/users updated",
        "spacebro-client/score::find => score-api/score::find",
        "spacebro-client/match::find => score-api/match::find"
]

write:

"connection": [
        "/users::find => score-api/users::find",
        "score-api/users updated => /users updated",
        "/score::find => score-api/score::find",
        "/match::find => score-api/match::find"
      ]

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.