-
Notifications
You must be signed in to change notification settings - Fork 0
service: pub-sub #141
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
glebfomin28
wants to merge
10
commits into
master
Choose a base branch
from
feature/pub-sub
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
service: pub-sub #141
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
6df5c30
feat(services): add pub-sub
glebfomin28 9140df7
chore(pub-sub): move types to a separate file
glebfomin28 194d918
feat(pub-sub): remove singleton and streamline class/types
glebfomin28 73fb12d
feat(pub-sub): added `unsubscribeAll` method
glebfomin28 130b64a
feat(pub-sub): added `subscribeOnce` method
glebfomin28 d8e72d2
feat(pub-sub): added `allSubscribes` method
glebfomin28 c04f8ad
chore(pub-sub): tests
glebfomin28 9304573
chore(pub-sub): updated readme
glebfomin28 72ed8eb
Merge branch 'master' into feature/pub-sub
pixel-fixer 87f20f4
рефакторинг PubSub
pixel-fixer File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| src |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| # `@byndyusoft-ui/pub-sub` | ||
|
|
||
| > A performant Pub/Sub interface with controlled instance management | ||
|
|
||
| ### Installation | ||
|
|
||
| ```bash | ||
| npm i @byndyusoft-ui/pub-sub | ||
| ``` | ||
|
|
||
| ## Usage | ||
|
|
||
| #### Import the class | ||
|
|
||
| ```ts | ||
| import PubSub from '@byndyusoft-ui/pub-sub'; | ||
| ``` | ||
|
|
||
| #### Define your channels | ||
| Create a type that defines the channels and their corresponding callback signatures. | ||
|
|
||
| ```ts | ||
| type ChannelsType = { | ||
| addTodo: (data: TodoType) => void; | ||
| removeTodo: (todoId: number) => void; | ||
| removeAll: () => void; | ||
| // For async callbacks: | ||
| asyncMessage: (data: string) => Promise<void>; | ||
| }; | ||
| ``` | ||
|
|
||
| #### Create an instance | ||
| ```ts | ||
| const pubSubInstance = new PubSub<ChannelsType>(); | ||
| ``` | ||
|
|
||
| #### Subscribe & Unsubscribe | ||
| Basic Subscription | ||
| ```ts | ||
| const addTodoCallback = (data: TodoType) => { | ||
| console.log('Added new todo:', data); | ||
| }; | ||
|
|
||
| // subscribe | ||
| pubSubInstance.subscribe('addTodo', addTodoCallback); | ||
|
|
||
| // unsubscribe | ||
| pubSubInstance.unsubscribe('addTodo', addTodoCallback); | ||
| ``` | ||
|
|
||
| #### One-Time Subscription | ||
| Use `subscribeOnce` to subscribe to an event that should be handled only once: | ||
|
|
||
| ```ts | ||
| pubSubInstance.subscribeOnce('addTodo', (data) => { | ||
| console.log('This callback will only be executed once:', data); | ||
| }); | ||
| ``` | ||
|
|
||
| #### Unsubscribe All | ||
| Remove all callbacks from a specific channel or from all channels: | ||
|
|
||
| ```ts | ||
| // Unsubscribe all from a specific channel | ||
| pubSubInstance.unsubscribeAll('addTodo'); | ||
|
|
||
| // Unsubscribe all from all channels | ||
| pubSubInstance.unsubscribeAll(); | ||
| ``` | ||
|
|
||
| #### Publish Events | ||
|
|
||
| Synchronous Publish | ||
|
|
||
| ```ts | ||
| pubSubInstance.publish('addTodo', { id: 1, text: 'Some todo'}); | ||
| ``` | ||
|
|
||
| Asynchronous Publish | ||
| Use `publishAsync` to publish data and wait for asynchronous subscribers: | ||
|
|
||
| ```ts | ||
| pubSubInstance.subscribe('asyncMessage', async (data) => { | ||
| await new Promise((resolve) => setTimeout(resolve, 1000)); | ||
| console.log(`Async received: ${data}`); | ||
| }); | ||
| ``` | ||
|
|
||
| #### Publish asynchronously | ||
| Use publishAsync to publish data and handle asynchronous subscribers. | ||
|
|
||
| ```ts | ||
|
|
||
| pubSubInstance.subscribe('asyncMessage', async (data) => { | ||
| await new Promise((resolve) => setTimeout(resolve, 1000)); | ||
| console.log(`Async received: ${data}`); | ||
| }); | ||
|
|
||
| await pubSubInstance.publishAsync('asyncMessage', 'This is asynchronous!'); | ||
| ``` | ||
|
|
||
|
|
||
| #### Get All Subscriptions | ||
| For debugging or monitoring, you can retrieve current subscriptions: | ||
|
|
||
| ```ts | ||
| const subscriptions = pubSubInstance.allSubscribes(); | ||
| console.log(subscriptions); | ||
| // Output example: | ||
| // [ { channel: 'addTodo', subscribers: 2 }, { channel: 'asyncMessage', subscribers: 1 } ] | ||
| ``` | ||
|
|
||
| #### Reset Subscriptions | ||
| Clear all channels and their subscribers: | ||
|
|
||
| ```ts | ||
| pubSubInstance.reset(); | ||
| ``` | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| { | ||
| "name": "@byndyusoft-ui/pub-sub", | ||
| "version": "0.0.1", | ||
| "description": "Byndyusoft UI Service", | ||
| "keywords": [ | ||
| "byndyusoft", | ||
| "byndyusoft-ui", | ||
| "channels", | ||
| "publish", | ||
| "subscribe", | ||
| "Pub/Sub" | ||
| ], | ||
| "author": "Gleb Fomin <gleb.fom28@gmail.com>", | ||
| "homepage": "https://github.com/Byndyusoft/ui/tree/master/services/pub-sub#readme", | ||
| "license": "Apache-2.0", | ||
| "main": "dist/index.js", | ||
| "types": "dist/index.d.ts", | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "git+https://github.com/Byndyusoft/ui.git" | ||
| }, | ||
| "scripts": { | ||
| "build": "tsc --project tsconfig.build.json", | ||
| "clean": "rimraf dist", | ||
| "lint": "eslint src --config ../../eslint.config.js", | ||
| "test": "jest --config ../../jest.config.js --roots services/pub-sub/src" | ||
| }, | ||
| "bugs": { | ||
| "url": "https://github.com/Byndyusoft/ui/issues" | ||
| }, | ||
| "publishConfig": { | ||
| "access": "public" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export { default } from './pubSub'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| import PubSub from './pubSub'; | ||
|
|
||
| describe('services/pub-sub', () => { | ||
| const pubSub = new PubSub(); | ||
|
|
||
| afterEach(() => { | ||
| pubSub.reset(); | ||
| }); | ||
|
|
||
| test('should subscribe and publish to a channel', () => { | ||
| const callback = jest.fn(); | ||
| pubSub.subscribe('testChannel', callback); | ||
|
|
||
| pubSub.publish('testChannel', 'Hello, World!'); | ||
|
|
||
| expect(callback).toHaveBeenCalledTimes(1); | ||
| expect(callback).toHaveBeenCalledWith('Hello, World!'); | ||
| }); | ||
|
|
||
| test('should not call callback if no subscribers', () => { | ||
| const callback = jest.fn(); | ||
| pubSub.publish('testChannel'); | ||
|
|
||
| expect(callback).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| test('should unsubscribe from a channel', () => { | ||
| const callback = jest.fn(); | ||
| pubSub.subscribe('testChannel', callback); | ||
| pubSub.unsubscribe('testChannel', callback); | ||
|
|
||
| pubSub.publish('testChannel'); | ||
|
|
||
| expect(callback).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| test('should handle async subscribe callbacks', async () => { | ||
| const asyncCallback = jest.fn().mockResolvedValue(undefined); | ||
| pubSub.subscribe('asyncChannel', asyncCallback); | ||
|
|
||
| await pubSub.publishAsync('asyncChannel', 'Async data'); | ||
|
|
||
| expect(asyncCallback).toHaveBeenCalledTimes(1); | ||
| expect(asyncCallback).toHaveBeenCalledWith('Async data'); | ||
| }); | ||
|
|
||
| test('should reset all subscriptions', () => { | ||
| const callback1 = jest.fn(); | ||
| const callback2 = jest.fn(); | ||
|
|
||
| pubSub.subscribe('testChannel', callback1); | ||
| pubSub.subscribe('testChannel', callback2); | ||
|
|
||
| pubSub.reset(); | ||
|
|
||
| pubSub.publish('testChannel'); | ||
|
|
||
| expect(callback1).not.toHaveBeenCalled(); | ||
| expect(callback2).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| test('should unsubscribe all callbacks for all channels using unsubscribeAll', () => { | ||
| const callback1 = jest.fn(); | ||
| const callback2 = jest.fn(); | ||
|
|
||
| pubSub.subscribe('testChannel', callback1); | ||
| pubSub.subscribe('asyncChannel', callback2); | ||
|
|
||
| pubSub.unsubscribeAll(); | ||
|
|
||
| pubSub.publish('testChannel', 'Test data'); | ||
| pubSub.publish('asyncChannel', 'Test data'); | ||
|
|
||
| expect(callback1).not.toHaveBeenCalled(); | ||
| expect(callback2).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| test('should call subscribeOnce callback only once', () => { | ||
| const callback = jest.fn(); | ||
| pubSub.subscribeOnce('testChannel', callback); | ||
|
|
||
| // First publish should trigger the callback. | ||
| pubSub.publish('testChannel', 'Test message 1'); | ||
|
|
||
| // Subsequent publish should not trigger the callback. | ||
| pubSub.publish('testChannel', 'Test message 2'); | ||
|
|
||
| expect(callback).toHaveBeenCalledTimes(1); | ||
| expect(callback).toHaveBeenCalledWith('Test message 1'); | ||
| }); | ||
|
|
||
| test('should return all subscriptions info', () => { | ||
| const callback1 = jest.fn(); | ||
| const callback2 = jest.fn(); | ||
|
|
||
| pubSub.subscribe('testChannel', callback1); | ||
| pubSub.subscribe('testChannel', callback2); | ||
| pubSub.subscribe('asyncChannel', callback1); | ||
|
|
||
| const result = pubSub.getAllSubscribers(); | ||
|
|
||
| const testChannelInfo = result.find(item => item.event === 'testChannel'); | ||
| const asyncChannelInfo = result.find(item => item.event === 'asyncChannel'); | ||
|
|
||
| expect(testChannelInfo).toBeDefined(); | ||
|
|
||
| expect(testChannelInfo?.subscribers.length).toBe(2); | ||
|
|
||
| expect(asyncChannelInfo).toBeDefined(); | ||
|
|
||
| expect(asyncChannelInfo?.subscribers.length).toBe(1); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| type Callback = (data: unknown) => void; | ||
|
|
||
| export default class PubSub { | ||
| private events: Map<string, Set<Callback>> = new Map(); | ||
|
|
||
| subscribe(event: string, callback: Callback): void { | ||
| if (!this.events.has(event)) { | ||
| this.events.set(event, new Set()); | ||
| } | ||
| this.events.get(event)!.add(callback); | ||
| } | ||
|
|
||
| subscribeOnce(event: string, callback: Callback): void { | ||
| const onceCallback: Callback = (data: unknown) => { | ||
| callback(data); // Execute the callback | ||
| this.unsubscribe(event, onceCallback); // Unsubscribe after execution | ||
| }; | ||
| this.subscribe(event, onceCallback); | ||
| } | ||
|
|
||
| publish(event: string, data: unknown = null): void { | ||
| if (this.events.has(event)) { | ||
| this.events.get(event)!.forEach(callback => callback(data)); | ||
| } | ||
| } | ||
|
|
||
| async publishAsync(event: string, data: unknown = null): Promise<void> { | ||
| if (this.events.has(event)) { | ||
| const callbacks = Array.from(this.events.get(event)!); | ||
| // Execute all callbacks concurrently | ||
| await Promise.all(callbacks.map(callback => callback(data))); | ||
| } | ||
| } | ||
|
|
||
| unsubscribe(event: string, callback: Callback): void { | ||
| if (this.events.has(event)) { | ||
| const callbacks = this.events.get(event)!; | ||
| callbacks.delete(callback); | ||
|
|
||
| // Clean up the event if no callbacks are left | ||
| if (callbacks.size === 0) { | ||
| this.events.delete(event); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| unsubscribeAll(event?: string): void { | ||
| if (event) { | ||
| if (this.events.has(event)) { | ||
| this.events.delete(event); | ||
| } | ||
| } else { | ||
| this.events.clear(); | ||
| } | ||
| } | ||
|
|
||
| reset(): void { | ||
| this.events.clear(); | ||
| } | ||
|
|
||
| getAllSubscribers(): { event: string; subscribers: Callback[] }[] { | ||
| return Array.from(this.events.entries()).map(([event, callbacks]) => { | ||
| return { event, subscribers: Array.from(callbacks) }; | ||
| }); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| { | ||
| "extends": "./tsconfig.json", | ||
| "exclude": ["src/*.tests.ts"] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| { | ||
| "extends": "../../tsconfig.json", | ||
| "compilerOptions": { | ||
| "declaration": true, | ||
| "declarationDir": "dist", | ||
| "outDir": "dist", | ||
| "module": "commonjs", | ||
| "target": "es6" | ||
| }, | ||
| "include": ["src"] | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вот этот тип мне кажется проблемой. С ним у нас есть место, которое должно знать о всех событиях, которые надо обрабатывать. Как будто бы появляется лишняя связь между разными частями приложения.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Согласен, с глобальным экземпляром есть такая проблема. Тут можно использовать pub-sub только внутри модуля, если это возможно. Или не типизировать глобальный экземпляр и делать адаптер в каждом модуле.