Skip to content

Commit

Permalink
feat: subscribe to array of events
Browse files Browse the repository at this point in the history
Signed-off-by: Abdelrahman Essawy <[email protected]>
  • Loading branch information
abdelrahman-essawy committed May 10, 2024
1 parent 883dd35 commit 9704f00
Show file tree
Hide file tree
Showing 8 changed files with 1,415 additions and 26 deletions.
8 changes: 8 additions & 0 deletions .changeset/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Changesets

Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets)

We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)
11 changes: 11 additions & 0 deletions .changeset/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"$schema": "https://unpkg.com/@changesets/[email protected]/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": false,
"fixed": [],
"linked": [],
"access": "restricted",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": []
}
5 changes: 5 additions & 0 deletions .changeset/smart-penguins-hide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@enegix/source': minor
---

allowing to subssribe to array of events
4 changes: 2 additions & 2 deletions libs/core/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@enegix/events",
"version": "0.0.2",
"name": "core",
"version": "0.1.2",
"license": "MIT",
"type": "commonjs",
"main": "./src/index.js",
Expand Down
81 changes: 77 additions & 4 deletions libs/core/src/lib/core.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,80 @@
import { core } from './core';
// Mock console.log to prevent output during testing
import { publish, subscribe, unsubscribeAll } from '@enegix/events';
import { expect, MockInstance, vitest } from 'vitest';

describe('core', () => {
it('should work', () => {
expect(core()).toEqual('core');
describe('subscribe function', () => {
let callbackSpy: MockInstance;

beforeEach(() => {
callbackSpy = vitest.spyOn(console, 'log');
});

afterEach(() => {
callbackSpy.mockRestore();
unsubscribeAll();
});

test('subscribing to a single event', () => {
const callback = console.log;
const { unsubscribe } = subscribe('event1', callback);

publish('event1', 'testData');

expect(callbackSpy).toHaveBeenCalledWith('testData');
expect(callbackSpy).toHaveBeenCalledWith(
'Published \'event1\' event with data: "testData"'
);
});

test('subscribing to multiple events', () => {
const callback = console.log;
const { unsubscribe } = subscribe(['event1', 'event2'], callback);

publish('event1', 'testData1');
publish('event2', 'testData2');

expect(callbackSpy).toHaveBeenCalledWith('testData1');
expect(callbackSpy).toHaveBeenCalledWith('testData2');
expect(callbackSpy).toHaveBeenCalledWith(
'Published \'event1\' event with data: "testData1"'
);
expect(callbackSpy).toHaveBeenCalledWith(
'Published \'event2\' event with data: "testData2"'
);
});

test('unsubscribe from event', () => {
const callback = console.log;
const { unsubscribe } = subscribe('event1', callback);

publish('event1', 'testData');
unsubscribe();
publish('event1', 'ignoreData');

expect(callbackSpy).toHaveBeenCalledWith(
'Published \'event1\' event with data: "testData"'
);
expect(callbackSpy).toHaveBeenCalledWith('testData');
expect(callbackSpy).not.toHaveBeenCalledWith('ignoreData');
});

test('unsubscribe from multiple events', () => {
const callback = console.log;
const { unsubscribe } = subscribe(['event1', 'event2'], callback);

publish('event1', 'testData1');
publish('event2', 'testData2');
unsubscribe();
publish('event1', 'testData1');
publish('event2', 'testData2');

expect(callbackSpy).toHaveBeenCalledWith('testData1');
expect(callbackSpy).toHaveBeenCalledWith('testData2');
expect(callbackSpy).toHaveBeenCalledWith(
'Published \'event1\' event with data: "testData1"'
);
expect(callbackSpy).toHaveBeenCalledWith(
'Published \'event2\' event with data: "testData2"'
);
});
});
45 changes: 30 additions & 15 deletions libs/core/src/lib/core.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,54 @@
import { EventEmitter } from 'eventemitter3';

export const emitter = new EventEmitter();
const emitter = new EventEmitter();

type Subscribe = (
event: string,
callback: (data: unknown) => void,
events: string | string[],
callback: (data: unknown) => void
) => {
data: unknown;
unsubscribe: () => void;
};

export const subscribe: Subscribe = (event, callback) => {
export const subscribe: Subscribe = (events, callback) => {
let eventList: string[];

if (typeof events === 'string') {
eventList = [events];
} else {
eventList = events;
}

let data;

const _callback = (_data: unknown) => {
data = _data;
callback(data);
console.log(`Received data: ${JSON.stringify(data)}`);
};

console.log(`Subscribed to event '${event}'`);

emitter.on(event, _callback);

// console.table({
// event: emitter.eventNames(),
// listeners: emitter.listenerCount(event),
// });
const unSubscriptions = eventList.map((event) => {
console.log(`Subscribed to event '${event}'`);
emitter.on(event, _callback);
return () => {
emitter.off(event, _callback);
console.log(`Unsubscribed from event '${event}'`);
};
});

const unsubscribe = () => {
emitter.off(event, _callback);
console.log(`Unsubscribed from event '${event}'`);
unSubscriptions.forEach((unsub) => {
unsub();
console.log(`Unsubscribed from event '${unsub.name}'`);
});
};

return { data, unsubscribe };
};

export const subscribeOnce = (
event: string,
callback: (data: unknown) => void,
callback: (data: unknown) => void
) => {
emitter.once(event, callback);
return { unsubscribe: () => emitter.off(event, callback) };
Expand All @@ -49,3 +60,7 @@ export const publish: Publish = (event, data) => {
emitter.emit(event, data);
console.log(`Published '${event}' event with data: ${JSON.stringify(data)}`);
};

export const unsubscribeAll = () => {
emitter.removeAllListeners();
};
6 changes: 2 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
{
"name": "@enegix/source",
"version": "0.0.2",
"license": "MIT",
"scripts": {
},
"scripts": {},
"publishConfig": {
"access": "public"
},
"private": true,
"devDependencies": {
"@changesets/cli": "^2.27.1",
"@nx/eslint": "18.2.3",
"@nx/eslint-plugin": "18.2.3",
"@nx/js": "18.3.1",
Expand Down
Loading

0 comments on commit 9704f00

Please sign in to comment.