Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

ts-simple-event-bus

Package Overview
Dependencies
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-simple-event-bus - npm Package Compare versions

Comparing version 1.1.5 to 2.0.0

2

dist/index.js

@@ -1,1 +0,1 @@

!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["ts-event-bus"]=t():e["ts-event-bus"]=t()}(this,(function(){return(()=>{"use strict";var e={225:function(e,t){var s=this&&this.__awaiter||function(e,t,s,i){return new(s||(s=Promise))((function(r,n){function o(e){try{c(i.next(e))}catch(e){n(e)}}function u(e){try{c(i.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,u)}c((i=i.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.EventBus=t.MessageTimeoutError=void 0;class i extends Error{constructor(e){super("Message timeout error"),this.message=`Message timeout error on message ${e}`}}t.MessageTimeoutError=i,t.EventBus=class{constructor(e){this.subcriptions=[],this.idGenerator=e}publish({queue:e,message:t,id:i}){return s(this,void 0,void 0,(function*(){this.subcriptions.forEach((r=>s(this,void 0,void 0,(function*(){r.queue===e&&r.callback(t,i)}))))}))}subscribe(e){const t=this.idGenerator();return this.subcriptions.push(Object.assign(Object.assign({},e),{id:t})),{unsubscribe:()=>{this.subcriptions=this.subcriptions.filter((e=>e.id!==t))}}}publishAndWaitForResponse({message:e,queue:t,responseQueue:s,timeout:r=5e3}){return new Promise(((n,o)=>{const u=this.idGenerator(),c=setTimeout((()=>{o(new i)}),r);this.subscribe({queue:s,callback:(e,t)=>{t===u&&(clearTimeout(c),n(e))}}),this.publish({queue:t,message:e,id:u})}))}}},607:function(e,t,s){var i=this&&this.__createBinding||(Object.create?function(e,t,s,i){void 0===i&&(i=s),Object.defineProperty(e,i,{enumerable:!0,get:function(){return t[s]}})}:function(e,t,s,i){void 0===i&&(i=s),e[i]=t[s]}),r=this&&this.__exportStar||function(e,t){for(var s in e)"default"===s||Object.prototype.hasOwnProperty.call(t,s)||i(t,e,s)};Object.defineProperty(t,"__esModule",{value:!0}),r(s(225),t)}},t={};return function s(i){var r=t[i];if(void 0!==r)return r.exports;var n=t[i]={exports:{}};return e[i].call(n.exports,n,n.exports,s),n.exports}(607)})()}));
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["ts-event-bus"]=t():e["ts-event-bus"]=t()}(this,(function(){return(()=>{"use strict";var e={225:function(e,t){var s=this&&this.__awaiter||function(e,t,s,r){return new(s||(s=Promise))((function(i,o){function n(e){try{c(r.next(e))}catch(e){o(e)}}function u(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(n,u)}c((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.EventBus=t.MessageTimeoutError=void 0;class r extends Error{constructor(e){super("Message timeout error"),this.message=`Message timeout error on message ${e}`}}t.MessageTimeoutError=r,t.EventBus=class{constructor(e){this.subcriptions=[],this.idGenerator=e}publish({queue:e,message:t,id:r}){return s(this,void 0,void 0,(function*(){this.subcriptions.forEach((i=>s(this,void 0,void 0,(function*(){i.queue===e&&i.callback(t,r)}))))}))}subscribe({queue:e,callback:t}){const s=this.idGenerator();return this.subcriptions.push({queue:e,callback:t,id:s}),{unsubscribe:()=>{this.subcriptions=this.subcriptions.filter((e=>e.id!==s))}}}publishAndWaitForResponse({message:e,queue:t,responseQueue:s,timeout:i=5e3}){return new Promise(((o,n)=>{const u=this.idGenerator(),c=setTimeout((()=>{n(new r)}),i);this.subscribe({queue:s,callback:(e,t)=>{t===u&&(clearTimeout(c),o(e))}}),this.publish({queue:t,message:e,id:u})}))}}},607:function(e,t,s){var r=this&&this.__createBinding||(Object.create?function(e,t,s,r){void 0===r&&(r=s),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[s]}})}:function(e,t,s,r){void 0===r&&(r=s),e[r]=t[s]}),i=this&&this.__exportStar||function(e,t){for(var s in e)"default"===s||Object.prototype.hasOwnProperty.call(t,s)||r(t,e,s)};Object.defineProperty(t,"__esModule",{value:!0}),i(s(225),t)}},t={};return function s(r){var i=t[r];if(void 0!==i)return i.exports;var o=t[r]={exports:{}};return e[r].call(o.exports,o,o.exports,s),o.exports}(607)})()}));
{
"name": "ts-simple-event-bus",
"version": "1.1.5",
"version": "2.0.0",
"main": "dist/index.js",

@@ -5,0 +5,0 @@ "types": "dist/index.d.ts",

@@ -5,2 +5,5 @@ # TS-simple-event-bus

### Version 2.XX
Version 2 adds a typing that is defined once at the bus initialisation.
## Use cases

@@ -14,2 +17,56 @@

// The typing is a nested object with queue names as keys and message payload as value
type EventBusTyping = {
queue: {
a: string;
b: number;
}
};
// Use a function to generate a unique id. You should provide the typing as well
const bus = new EventBus<EventBusTyping>(uuid);
bus.subscribe({ queue: "queue", callback: (message) => {
console.log(message.id, message.a, message.b);
} });
bus.publish({ queue: "queue", { a: "a", b: 1 } });
```
Waiting for a response:
```typescript
type EventBusTyping = {
queue: {
a: string;
b: number;
}
};
const bus = new EventBus<EventBusTyping>(idGenerator);
const responseQueueName = "event-response";
bus.subscribe({
queue: "event-request",
callback: (msg, id) => {
bus.publish({ queue: responseQueueName, message: { event: "response" }, id });
},
});
const result = await bus.publishAndWaitForResponse({
queue: "event-request",
responseQueue: responseQueueName,
message: { event: "request" },
timeout: 1000,
});
// result will be { event: "response" }
```
### Version 1.XX
## Use cases
Simple publish and subscribe:
```typescript
import { EventBus, Callback } from "ts-simple-event-bus";
import { uuid } from "uuid";
type MessagePayload = {

@@ -16,0 +73,0 @@ a: string;

@@ -13,9 +13,15 @@ import chai from "chai";

it("Doesn't receive a message published to channel not subscribed to", () => {
const bus = new EventBus(idGenerator);
type BusType = {
queue: {
truc: string;
};
};
const bus = new EventBus<BusType>(idGenerator);
const callback: Callback<{ truc: string }> = (message) => {};
const spiedCallback = chai.spy(callback);
bus.subscribe<{ truc: string }>({ queue: "queue", callback: spiedCallback });
bus.subscribe({ queue: "queue", callback: spiedCallback });
bus.publish<{ truc: string }>({ queue: "notqueue", message: { truc: "truc" } });
//@ts-expect-error
bus.publish({ queue: "notqueue", message: { truc: "truc" } });

@@ -25,7 +31,12 @@ expect(spiedCallback).to.not.have.been.called.once;

it("Receives the message published to a channel which is subscribed to", () => {
const bus = new EventBus(idGenerator);
type BusType = {
queue: {
truc: string;
};
};
const bus = new EventBus<BusType>(idGenerator);
const callback: Callback<{ truc: string }> = (message) => {};
const spiedCallback = chai.spy(callback);
bus.subscribe<{ truc: string }>({ queue: "queue", callback: spiedCallback });
bus.subscribe({ queue: "queue", callback: spiedCallback });

@@ -38,7 +49,12 @@ bus.publish({ queue: "queue", message: { truc: "truc" } });

it("Can unsubscribe to a channel", () => {
const bus = new EventBus(idGenerator);
type BusType = {
queue: {
truc: string;
};
};
const bus = new EventBus<BusType>(idGenerator);
const callback: Callback<{ truc: string }> = (message) => {};
const spiedCallback = chai.spy(callback);
const { unsubscribe } = bus.subscribe<{ truc: string }>({ queue: "queue", callback: spiedCallback });
const { unsubscribe } = bus.subscribe({ queue: "queue", callback: spiedCallback });
unsubscribe();

@@ -51,3 +67,11 @@ bus.publish({ queue: "queue", message: { truc: "truc" } });

it("Can publish and wait for response", async () => {
const bus = new EventBus(idGenerator);
type BusType = {
"event-request": {
truc: string;
};
"event-response": {
truc: string;
};
};
const bus = new EventBus<BusType>(idGenerator);
const responseQueueName = "event-response";

@@ -70,3 +94,11 @@ bus.subscribe({

it("Will throw MessageTimeoutError if publishAndWaitForResponse does not complete in time", async () => {
const bus = new EventBus(idGenerator);
type BusType = {
"event-request": {
truc: string;
};
"event-response": {
truc: string;
};
};
const bus = new EventBus<BusType>(idGenerator);
await expect(

@@ -83,3 +115,11 @@ bus.publishAndWaitForResponse({

it("Can handle Promise response", async () => {
const bus = new EventBus(idGenerator);
type BusType = {
"event-request": {
truc: string;
};
"event-response": {
trac: string;
};
};
const bus = new EventBus<BusType>(idGenerator);
const responseQueueName = "event-response";

@@ -91,3 +131,3 @@ bus.subscribe({

const timeoutId = setTimeout(() => {
bus.publish({ queue: responseQueueName, message: { truc: "response" }, id });
bus.publish({ queue: responseQueueName, message: { trac: "response" }, id });
req();

@@ -105,4 +145,4 @@ clearTimeout(timeoutId);

});
expect(result).to.deep.equal({ truc: "response" });
expect(result).to.deep.equal({ trac: "response" });
});
});
});

@@ -7,3 +7,3 @@ type Queue = string;

id: string;
queue: Queue;
queue: keyof T;
callback: Callback<T>;

@@ -22,3 +22,4 @@ };

}
export class EventBus {
export class EventBus<T> {
private subcriptions: Subscription<any>[] = [];

@@ -31,3 +32,3 @@ private idGenerator: IdGenerator;

async publish<T>({ queue, message, id }: { queue: Queue; message: Message<T>; id?: string }) {
async publish<Q extends keyof T>({ queue, message, id }: { queue: Q; message: T[Q]; id?: string }) {
this.subcriptions.forEach(async (sub) => {

@@ -40,5 +41,11 @@ if (sub.queue === queue) {

subscribe<T = any>(subscription: Omit<Subscription<T>, "id">) {
subscribe<Q extends keyof T>({
queue,
callback,
}: {
queue: Q;
callback: (message: T[Q] & { id?: string }, id?: string) => void | Promise<void>;
}) {
const id = this.idGenerator();
this.subcriptions.push({ ...subscription, id });
this.subcriptions.push({ queue, callback, id });
return {

@@ -51,3 +58,3 @@ unsubscribe: () => {

publishAndWaitForResponse<Req, Rep>({
publishAndWaitForResponse<Q extends keyof T, RQ extends keyof T>({
message,

@@ -58,7 +65,7 @@ queue,

}: {
queue: Queue;
responseQueue: string;
message: Message<Req>;
queue: Q;
responseQueue: RQ;
message: T[Q] & { id?: string };
timeout?: number;
}): Promise<Rep> {
}): Promise<T[RQ]> {
return new Promise((res, rej) => {

@@ -70,3 +77,3 @@ const msgId = this.idGenerator();

this.subscribe<Rep>({
this.subscribe({
queue: responseQueue,

@@ -81,5 +88,5 @@ callback: (handledMessage, id) => {

this.publish<Req>({ queue, message, id: msgId });
this.publish({ queue, message, id: msgId });
});
}
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc