All Projects → Dashlane → Ts Event Bus

Dashlane / Ts Event Bus

Licence: apache-2.0
📨 Distributed messaging in TypeScript

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Ts Event Bus

Deno Websocket
🦕 A simple WebSocket library like ws of node.js library for deno
Stars: ✭ 74 (-12.94%)
Mutual labels:  websocket
Fluxxan
Fluxxan is an Android implementation of the Flux Architecture that combines concepts from both Fluxxor and Redux.
Stars: ✭ 80 (-5.88%)
Mutual labels:  eventbus
Bufferutil
WebSocket buffer utils
Stars: ✭ 83 (-2.35%)
Mutual labels:  websocket
Huobi golang
Go SDK for Huobi Spot API
Stars: ✭ 76 (-10.59%)
Mutual labels:  websocket
Bilibili Live Ws
Bilibili live WebSocket/tcp API
Stars: ✭ 79 (-7.06%)
Mutual labels:  websocket
Angular Websocket
↖️ The missing Angular WebSocket module for connecting client applications to servers by @AngularClass
Stars: ✭ 1,242 (+1361.18%)
Mutual labels:  websocket
Wscelery
Real time celery monitoring using websockets
Stars: ✭ 76 (-10.59%)
Mutual labels:  websocket
Chat Room
一个普通的聊天室
Stars: ✭ 85 (+0%)
Mutual labels:  websocket
Deepspeech Websocket Server
Server & client for DeepSpeech using WebSockets for real-time speech recognition in separate environments
Stars: ✭ 79 (-7.06%)
Mutual labels:  websocket
Wstest
go websocket client for unit testing of a websocket handler
Stars: ✭ 83 (-2.35%)
Mutual labels:  websocket
Gowebsocket
Gorilla websockets based simplified websocket-client implementation in GO.
Stars: ✭ 77 (-9.41%)
Mutual labels:  websocket
Ptt Client
A Node.js/Browser client for fetching data from ptt.cc
Stars: ✭ 78 (-8.24%)
Mutual labels:  websocket
Resugan
simple, powerful and unobstrusive event driven architecture framework for ruby
Stars: ✭ 82 (-3.53%)
Mutual labels:  eventbus
Bilibili danmuji
(Bilibili)B站直播礼物答谢、定时广告、关注感谢,自动回复工具,房管工具,自动打卡,Bilibili直播弹幕姬(使用websocket协议),java版B站弹幕姬,基于springboot。
Stars: ✭ 76 (-10.59%)
Mutual labels:  websocket
Rabbitevents
Nuwber's events provide a simple observer implementation, allowing you to listen for various events that occur in your current and another application. For example, if you need to react to some event published from another API.
Stars: ✭ 84 (-1.18%)
Mutual labels:  eventbus
Noduino
JavaScript and Node.js Framework for controlling Arduino with HTML and WebSockets
Stars: ✭ 1,202 (+1314.12%)
Mutual labels:  websocket
Laplace
Laplace is an open-source project to enable screen sharing directly via browser. Based on WebRTC for low latency peer-to-peer connections, and WebSocket implemented in golang for signaling.
Stars: ✭ 81 (-4.71%)
Mutual labels:  websocket
Blockchain Kotlin
这是kotlin版的简化示例区块链demo;另外还有java版的;这个小demo能让你了解区块链中增加/效验Hash,增加工作量证明,增加/效验preHash,转账,利用webSocket技术实现节点之间的通信/同步/广播.
Stars: ✭ 85 (+0%)
Mutual labels:  websocket
Pywebsocketserver
python的websocket server
Stars: ✭ 84 (-1.18%)
Mutual labels:  websocket
Laverna
Laverna is a JavaScript note taking application with Markdown editor and encryption support. Consider it like open source alternative to Evernote.
Stars: ✭ 8,770 (+10217.65%)
Mutual labels:  websocket

ts-event-bus

by Dashlane

Build Status Dependency Status

Distributed messaging in Typescript

ts-event-bus is a lightweight distributed messaging system. It allows several modules, potentially distributed over different runtime spaces to communicate through typed messages.

Getting started

Declare your events

Using ts-event-bus starts with the declaration of the interface that your components share:

// MyEvents.ts
import { slot, Slot } from 'ts-event-bus'

const MyEvents = {
    sayHello: slot<string>(),
    getTime: slot<null, string>(),
    multiply: slot<{a: number, b: number}, number>(),
    ping: slot<void>(),
}

export default MyEvents

Create EventBus

Your components will then instantiate an event bus based on this declaration, using whatever channel they may want to communicate on. If you specify no Channel, it means that you will exchange events in the same memory space.

For instance, one could connect two node processes over WebSocket:

// firstModule.EventBus.ts
import { createEventBus } from 'ts-event-bus'
import MyEvents from './MyEvents.ts'
import MyBasicWebSocketClientChannel from './MyBasicWebSocketClientChannel.ts'

const EventBus = createEventBus({
    events: MyEvents,
    channels: [ new MyBasicWebSocketClientChannel('ws://your_host') ]
})

export default EventBus
// secondModule.EventBus.ts
import { createEventBus } from 'ts-event-bus'
import MyEvents from './MyEvents.ts'
import MyBasicWebSocketServerChannel from './MyBasicWebSocketServerChannel.ts'

const EventBus = createEventBus({
    events: MyEvents,
    channels: [ new MyBasicWebSocketServerChannel('ws://your_host') ]
})

Usage

Once connected, the clients can start by using the slots on the event bus

// firstModule.ts
import EventBus from './firstModule.EventBus.ts'

// Slots can be called with a parameter, here 'michel'
EventBus.say('michel', 'Hello')

// Or one can rely on the default parameter: here DEFAULT_PARAMETER
// is implicitely used.
EventBus.say('Hello')

// Triggering an event always returns a promise
EventBus.say('michel', 'Hello').then(() => {
    ...
})

EventBus.getTime().then((time) => {
    ...
})

EventBus.multiply({a: 2, b: 5 }).then((result) => {
    ...
})

EventBus.ping()
// secondModule.ts
import EventBus from './secondModule.EventBus.ts'

// Add a listener on the default parameter
EventBus.ping.on(() => {
    console.log('pong')
})

// Or listen to a specific parameter
EventBus.say.on('michel', (words) => {
    console.log('michel said', words)
})

// Event subscribers can respond to the event synchronously (by returning a value)
EventBus.getTime.on(() => new Date().toString)

// Or asynchronously (by returning a Promise that resolves with the value).
EventBus.multiply.on(({ a, b }) => new Promise((resolve, reject) => {
    AsynchronousMultiplier(a, b, (err, result) => {
        if (err) {
            return reject(err)
        }
        resolve(result)
    })
}))

Calls and subscriptions on slots are typechecked

EventBus.multiply({a: 1, c: 2}) // Compile error: property 'c' does not exist on type {a: number, b: number}

EventBus.multiply.on(({a, b}) => {
    if (a.length > 2) { // Compile error: property 'length' does not exist on type 'number'
        ...
    }
})

Lazy callbacks

Slots expose a lazy method that will allow you to call a "connect" callback when a first client connects to the slot, and a "disconnect" callback when the last client disconnect.

Remote or local clients are considered equally. If a client was already connected to the slot at the time when lazy is called, the "connect" callback is called immediately.

const connect = (param) => {
  console.log(`Someone somewhere has begun listening to the slot with .on on ${param}.`)
}

const disconnect = (param) => {
  console.log(`No one is listening to the slot anymore on ${param}.`)
}

const disconnectLazy = EventBus.ping.lazy(connect, disconnect)

const unsubscribe = EventBus.ping().on(() => { })
// console output: 'Someone somewhere has begun listening to the slot with .on on $_DEFAULT_$.'

unsubscribe()
// console output: 'No one is listening to the slot anymore on $_DEFAULT_$.'

const unsubscribe = EventBus.ping().on('parameter', () => { })
// console output: 'Someone somewhere has begun listening to the slot with .on on parameter.'

unsubscribe()
// console output: 'No one is listening to the slot anymore on parameter.'

// Remove the callbacks.
// "disconnect" is called one last time if there were subscribers left on the slot.
disconnectLazy()

Buffering

When the eventBus is created with channels, slots will wait for all transports to have registered callbacks before triggering.

This buffering mechanism can be disabled at the slot level with the noBuffer config option:

const MyEvents = {
    willWait: slot<string>(),
    wontWait: slot<string>({ noBuffer: true }),
}

Syntactic sugar

You can combine events from different sources.

import { combineEvents } from 'ts-event-bus'
import MyEvents from './MyEvents.ts'
import MyOtherEvents from './MyOtherEvents.ts'

const MyCombinedEvents = combineEvents(
    MyEvents,
    MyOtherEvents,
)

export default MyCombinedEvents

Using and Implementing Channels

ts-event-bus comes with an abstract class GenericChannel. To implement your own channel create a new class extending GenericChannel, and call the method given by the abstract class: _connected(), _disconnected(), _error(e: Error) and _messageReceived(data: any).

Basic WebSocket Channel example:

import { GenericChannel } from 'ts-event-bus'

export class MyBasicWebSocketChannel extends GenericChannel {
    private _ws: WebSocket | null = null
    private _host: string

    constructor(host: string) {
        super()
        this._host = host
        this._init()
    }

    private _init(): void {
        const ws = new WebSocket(this._host)

        ws.onopen = (e: Event) => {
            this._connected()
            this._ws = ws
        }

        ws.onerror = (e: Event) => {
            this._ws = null
            this._error(e)
            this._disconnected()
            setTimeout(() => {
                this._init()
            }, 2000)
        }

        ws.onclose = (e: CloseEvent) => {
            if (ws === this._ws) {
                this._ws = null
                this._disconnected()
                this._init()
            }
        }

        ws.onmessage = (e: MessageEvent) => {
            this._messageReceived(e.data)
        }
    }
}

Examples

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].