@my-nestjs-kit/channels 0.0.0-stage → 0.1.0-dev.20261129020438
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +33 -2
- package/dist/channel-listener.decorator.d.ts +31 -0
- package/dist/channel-listener.decorator.js +34 -0
- package/dist/channel-listeners.explorer.d.ts +20 -0
- package/dist/channel-listeners.explorer.js +127 -0
- package/dist/channel-transport.d.ts +32 -0
- package/dist/channel-transport.js +51 -0
- package/dist/channels-module.options.d.ts +15 -0
- package/dist/channels-module.options.js +7 -0
- package/dist/channels-publisher.d.ts +12 -0
- package/dist/channels-publisher.js +51 -0
- package/dist/channels.constants.d.ts +3 -0
- package/dist/channels.constants.js +6 -0
- package/dist/channels.module.d.ts +12 -0
- package/dist/channels.module.js +47 -0
- package/dist/channels.types.d.ts +41 -0
- package/dist/channels.types.js +2 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +26 -0
- package/package.json +90 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 sabationok
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,34 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @my-nestjs-kit/channels
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Cross-instance pub/sub channels for NestJS. Depends on `@my-nestjs-kit/events` (its `/pipeline` only).
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm i @my-nestjs-kit/channels
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Peers: `@nestjs/common`, `@nestjs/core`, `reflect-metadata`, `ioredis` (types of the ioredis transport).
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
declare module '@my-nestjs-kit/channels' {
|
|
13
|
+
interface DefaultChannelsMap {
|
|
14
|
+
orders: { created: { id: string } };
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
ChannelsModule.forRoot({ transport: new IoRedisChannelTransport(pub, sub), serverId, prefix: 'app' });
|
|
19
|
+
|
|
20
|
+
@ChannelListener('orders', { ignoreOwn: true })
|
|
21
|
+
class OrdersChannel {
|
|
22
|
+
@OnChannelEvent('created') onCreated(data: { id: string }) {}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
publisher.publish('orders', 'created', { id }); // or publisher.of('orders').publish('created', { id })
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
`sub` must be a dedicated connection. Envelope: `{ channel, type, data, from: { serverId }, to?, timestamp }`.
|
|
29
|
+
Exact handlers run before `'*'`, by `priority`, through the same guards / interceptors / filters as the events bus.
|
|
30
|
+
`InMemoryChannelTransport` for tests and single-instance apps.
|
|
31
|
+
|
|
32
|
+
## License
|
|
33
|
+
|
|
34
|
+
MIT
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import 'reflect-metadata';
|
|
2
|
+
import { CHANNEL_ANY_EVENT } from './channels.constants';
|
|
3
|
+
import type { EventHandlerOptions } from '@my-nestjs-kit/events/pipeline';
|
|
4
|
+
import type { AnyChannelEventName, ChannelMessage, ChannelName, ChannelsMap, DefaultChannelsMap } from './channels.types';
|
|
5
|
+
export interface ChannelListenerOptions {
|
|
6
|
+
/** Skip messages this instance published itself (`from.serverId`). Default false. */
|
|
7
|
+
ignoreOwn?: boolean;
|
|
8
|
+
}
|
|
9
|
+
export interface ChannelListenerMeta extends ChannelListenerOptions {
|
|
10
|
+
channel: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Marks a provider as the listener of one channel, like `@Controller` for a route prefix.
|
|
14
|
+
* Its `@OnChannelEvent` methods are subscribed automatically (no manual `subscribe()`).
|
|
15
|
+
*/
|
|
16
|
+
export declare function ChannelListener<C extends ChannelName<M>, M extends ChannelsMap = DefaultChannelsMap>(channel: C, options?: ChannelListenerOptions): ClassDecorator;
|
|
17
|
+
export declare namespace ChannelListener {
|
|
18
|
+
var KEY: string;
|
|
19
|
+
}
|
|
20
|
+
export interface ChannelHandlerMeta {
|
|
21
|
+
type: string;
|
|
22
|
+
options: EventHandlerOptions;
|
|
23
|
+
}
|
|
24
|
+
export type ChannelHandlerDescriptor<Data> = TypedPropertyDescriptor<(data: Data, message: ChannelMessage, ...args: any[]) => unknown>;
|
|
25
|
+
/**
|
|
26
|
+
* Handler of one event of the class' channel (`'*'` = any event). Gets `(data, message)`.
|
|
27
|
+
* `@UseEventGuards` / `@UseEventInterceptors` / `@UseEventFilters` apply, as for in-process events.
|
|
28
|
+
* The key is checked against the events of all declared channels (a method decorator can't see
|
|
29
|
+
* the class' channel); type `data` in the handler signature.
|
|
30
|
+
*/
|
|
31
|
+
export declare function OnChannelEvent<K extends AnyChannelEventName<M> | typeof CHANNEL_ANY_EVENT, M extends ChannelsMap = DefaultChannelsMap>(type: K, options?: EventHandlerOptions): <D extends ChannelHandlerDescriptor<any>>(target: object, propertyKey: string | symbol, descriptor: D) => void;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.OnChannelEvent = exports.ChannelListener = void 0;
|
|
4
|
+
require("reflect-metadata");
|
|
5
|
+
const core_1 = require("@nestjs/core");
|
|
6
|
+
const channels_constants_1 = require("./channels.constants");
|
|
7
|
+
// TODO(kit): a per-channel decorator factory — `createChannelDecorators(channel)` → `{ Subscriber/ChListener, Publisher,
|
|
8
|
+
// OnEv, OnMsg, OnCmd }` made once per channel, so handler keys are checked against that channel only — and message
|
|
9
|
+
// types `cmd` (one handler) / `ev` / `msg` (many) as key prefixes. Exists in webhooxy:
|
|
10
|
+
// packages/api/src/redis/decorators/channel-handler.decorator.ts (+ base/redis-channel-sub.base.ts); in fintrack:
|
|
11
|
+
// apps/api/src/common/channels/ (`createChannelListenerDecorators`, `ChannelListenerBase.dispatch`).
|
|
12
|
+
const discoverable = core_1.DiscoveryService.createDecorator();
|
|
13
|
+
/**
|
|
14
|
+
* Marks a provider as the listener of one channel, like `@Controller` for a route prefix.
|
|
15
|
+
* Its `@OnChannelEvent` methods are subscribed automatically (no manual `subscribe()`).
|
|
16
|
+
*/
|
|
17
|
+
function ChannelListener(channel, options = {}) {
|
|
18
|
+
return discoverable({ ...options, channel });
|
|
19
|
+
}
|
|
20
|
+
exports.ChannelListener = ChannelListener;
|
|
21
|
+
ChannelListener.KEY = discoverable.KEY;
|
|
22
|
+
/**
|
|
23
|
+
* Handler of one event of the class' channel (`'*'` = any event). Gets `(data, message)`.
|
|
24
|
+
* `@UseEventGuards` / `@UseEventInterceptors` / `@UseEventFilters` apply, as for in-process events.
|
|
25
|
+
* The key is checked against the events of all declared channels (a method decorator can't see
|
|
26
|
+
* the class' channel); type `data` in the handler signature.
|
|
27
|
+
*/
|
|
28
|
+
function OnChannelEvent(type, options = {}) {
|
|
29
|
+
return (_target, _key, descriptor) => {
|
|
30
|
+
const current = Reflect.getMetadata(channels_constants_1.CHANNEL_HANDLER_METADATA, descriptor.value) ?? [];
|
|
31
|
+
Reflect.defineMetadata(channels_constants_1.CHANNEL_HANDLER_METADATA, [...current, { type, options }], descriptor.value);
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
exports.OnChannelEvent = OnChannelEvent;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
|
|
2
|
+
import { DiscoveryService, MetadataScanner, ModuleRef } from '@nestjs/core';
|
|
3
|
+
import { ChannelsModuleOptions } from './channels-module.options';
|
|
4
|
+
/**
|
|
5
|
+
* Finds `@ChannelListener` providers, builds each handler's pipeline, subscribes the transport
|
|
6
|
+
* to their channels and routes incoming messages: exact-type handlers, then `'*'` handlers.
|
|
7
|
+
*/
|
|
8
|
+
export declare class ChannelListenersExplorer implements OnApplicationBootstrap, OnApplicationShutdown {
|
|
9
|
+
private readonly discovery;
|
|
10
|
+
private readonly scanner;
|
|
11
|
+
private readonly options;
|
|
12
|
+
private readonly logger;
|
|
13
|
+
private readonly enhancers;
|
|
14
|
+
private readonly routes;
|
|
15
|
+
constructor(discovery: DiscoveryService, scanner: MetadataScanner, moduleRef: ModuleRef, options: ChannelsModuleOptions);
|
|
16
|
+
onApplicationBootstrap(): Promise<void>;
|
|
17
|
+
onApplicationShutdown(): Promise<void>;
|
|
18
|
+
/** Parses and routes one transport message. Resolves when every handler finished. */
|
|
19
|
+
dispatch(transportChannel: string, raw: string): Promise<void>;
|
|
20
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.ChannelListenersExplorer = void 0;
|
|
16
|
+
const common_1 = require("@nestjs/common");
|
|
17
|
+
const core_1 = require("@nestjs/core");
|
|
18
|
+
const pipeline_1 = require("@my-nestjs-kit/events/pipeline");
|
|
19
|
+
const pipeline_2 = require("@my-nestjs-kit/events/pipeline");
|
|
20
|
+
const channel_listener_decorator_1 = require("./channel-listener.decorator");
|
|
21
|
+
const channels_constants_1 = require("./channels.constants");
|
|
22
|
+
const channels_module_options_1 = require("./channels-module.options");
|
|
23
|
+
/**
|
|
24
|
+
* Finds `@ChannelListener` providers, builds each handler's pipeline, subscribes the transport
|
|
25
|
+
* to their channels and routes incoming messages: exact-type handlers, then `'*'` handlers.
|
|
26
|
+
*/
|
|
27
|
+
let ChannelListenersExplorer = class ChannelListenersExplorer {
|
|
28
|
+
constructor(discovery, scanner, moduleRef, options) {
|
|
29
|
+
this.discovery = discovery;
|
|
30
|
+
this.scanner = scanner;
|
|
31
|
+
this.options = options;
|
|
32
|
+
this.logger = new common_1.Logger('ChannelListeners');
|
|
33
|
+
this.routes = new Map();
|
|
34
|
+
this.enhancers = new pipeline_1.EventEnhancersResolver(moduleRef, options);
|
|
35
|
+
}
|
|
36
|
+
async onApplicationBootstrap() {
|
|
37
|
+
const byChannel = new Map();
|
|
38
|
+
for (const wrapper of this.discovery.getProviders({
|
|
39
|
+
metadataKey: channel_listener_decorator_1.ChannelListener.KEY,
|
|
40
|
+
})) {
|
|
41
|
+
const { instance } = wrapper;
|
|
42
|
+
if (!instance || typeof instance !== 'object')
|
|
43
|
+
continue;
|
|
44
|
+
const meta = Reflect.getMetadata(channel_listener_decorator_1.ChannelListener.KEY, instance.constructor);
|
|
45
|
+
const entry = byChannel.get(meta.channel) ?? {
|
|
46
|
+
ignoreOwn: !!meta.ignoreOwn,
|
|
47
|
+
handlers: new Map(),
|
|
48
|
+
};
|
|
49
|
+
entry.ignoreOwn ||= !!meta.ignoreOwn;
|
|
50
|
+
const prototype = Object.getPrototypeOf(instance);
|
|
51
|
+
for (const methodKey of this.scanner.getAllMethodNames(prototype)) {
|
|
52
|
+
const handler = prototype[methodKey];
|
|
53
|
+
const metas = Reflect.getMetadata(channels_constants_1.CHANNEL_HANDLER_METADATA, handler) ?? [];
|
|
54
|
+
for (const m of metas) {
|
|
55
|
+
const pattern = `${meta.channel}:${m.type}`;
|
|
56
|
+
const pipeline = await this.enhancers.pipelineFor(instance.constructor, handler, m.options.suppressErrors);
|
|
57
|
+
const list = entry.handlers.get(m.type) ?? [];
|
|
58
|
+
list.push({
|
|
59
|
+
pattern,
|
|
60
|
+
instance,
|
|
61
|
+
handler,
|
|
62
|
+
options: m.options,
|
|
63
|
+
pipeline,
|
|
64
|
+
});
|
|
65
|
+
entry.handlers.set(m.type, list);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
byChannel.set(meta.channel, entry);
|
|
69
|
+
}
|
|
70
|
+
for (const [channel, { ignoreOwn, handlers }] of byChannel) {
|
|
71
|
+
const dispatchers = new Map();
|
|
72
|
+
for (const [type, list] of handlers) {
|
|
73
|
+
list.sort((a, b) => (b.options.priority ?? 0) - (a.options.priority ?? 0));
|
|
74
|
+
dispatchers.set(type, (0, pipeline_2.createEventDispatcher)(`${channel}:${type}`, list, this.logger));
|
|
75
|
+
}
|
|
76
|
+
this.routes.set((0, channels_module_options_1.toTransportChannel)(this.options.prefix, channel), {
|
|
77
|
+
channel,
|
|
78
|
+
ignoreOwn,
|
|
79
|
+
dispatchers,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
await this.options.transport.subscribe([...this.routes.keys()], (ch, raw) => {
|
|
83
|
+
void this.dispatch(ch, raw);
|
|
84
|
+
});
|
|
85
|
+
if (this.routes.size)
|
|
86
|
+
this.logger.log(`Subscribed: ${[...this.routes.values()].map((r) => r.channel).join(', ')}`);
|
|
87
|
+
}
|
|
88
|
+
async onApplicationShutdown() {
|
|
89
|
+
await this.options.transport.close?.();
|
|
90
|
+
}
|
|
91
|
+
/** Parses and routes one transport message. Resolves when every handler finished. */
|
|
92
|
+
async dispatch(transportChannel, raw) {
|
|
93
|
+
const route = this.routes.get(transportChannel);
|
|
94
|
+
if (!route)
|
|
95
|
+
return;
|
|
96
|
+
let message;
|
|
97
|
+
try {
|
|
98
|
+
message = JSON.parse(raw);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
this.logger.warn(`${route.channel}: message is not JSON, dropped`);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (!message || typeof message.type !== 'string') {
|
|
105
|
+
this.logger.warn(`${route.channel}: message without a type, dropped`);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (route.ignoreOwn && message.from?.serverId === this.options.serverId)
|
|
109
|
+
return;
|
|
110
|
+
const type = `${route.channel}:${message.type}`;
|
|
111
|
+
for (const key of [message.type, channels_constants_1.CHANNEL_ANY_EVENT]) {
|
|
112
|
+
const dispatcher = route.dispatchers.get(key);
|
|
113
|
+
if (dispatcher)
|
|
114
|
+
await dispatcher
|
|
115
|
+
.call({ event: type }, message.data, message)
|
|
116
|
+
.catch((error) => this.logger.error(error));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
exports.ChannelListenersExplorer = ChannelListenersExplorer;
|
|
121
|
+
exports.ChannelListenersExplorer = ChannelListenersExplorer = __decorate([
|
|
122
|
+
(0, common_1.Injectable)(),
|
|
123
|
+
__param(3, (0, common_1.Inject)(channels_constants_1.CHANNELS_MODULE_OPTIONS)),
|
|
124
|
+
__metadata("design:paramtypes", [core_1.DiscoveryService,
|
|
125
|
+
core_1.MetadataScanner,
|
|
126
|
+
core_1.ModuleRef, Object])
|
|
127
|
+
], ChannelListenersExplorer);
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type Redis from 'ioredis';
|
|
2
|
+
export type ChannelMessageHandler = (channel: string, message: string) => void;
|
|
3
|
+
/** Pub/sub transport the channels run on. Receives already-prefixed channel names. */
|
|
4
|
+
export interface ChannelTransport {
|
|
5
|
+
publish(channel: string, message: string): Promise<unknown>;
|
|
6
|
+
subscribe(channels: string[], onMessage: ChannelMessageHandler): Promise<void>;
|
|
7
|
+
close?(): Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* ioredis transport. `sub` must be a dedicated connection — a connection in subscribe mode can't
|
|
11
|
+
* run other commands (`pub.duplicate()` is a good source).
|
|
12
|
+
*/
|
|
13
|
+
export declare class IoRedisChannelTransport implements ChannelTransport {
|
|
14
|
+
private readonly pub;
|
|
15
|
+
private readonly sub;
|
|
16
|
+
private handler?;
|
|
17
|
+
constructor(pub: Redis, sub: Redis);
|
|
18
|
+
publish(channel: string, message: string): Promise<number>;
|
|
19
|
+
subscribe(channels: string[], onMessage: ChannelMessageHandler): Promise<void>;
|
|
20
|
+
close(): Promise<void>;
|
|
21
|
+
}
|
|
22
|
+
/** Single-process transport: delivery on the next tick. For tests and one-instance setups. */
|
|
23
|
+
export declare class InMemoryChannelTransport implements ChannelTransport {
|
|
24
|
+
private readonly subscribed;
|
|
25
|
+
private handler?;
|
|
26
|
+
readonly published: {
|
|
27
|
+
channel: string;
|
|
28
|
+
message: string;
|
|
29
|
+
}[];
|
|
30
|
+
publish(channel: string, message: string): Promise<0 | 1>;
|
|
31
|
+
subscribe(channels: string[], onMessage: ChannelMessageHandler): Promise<void>;
|
|
32
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.InMemoryChannelTransport = exports.IoRedisChannelTransport = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* ioredis transport. `sub` must be a dedicated connection — a connection in subscribe mode can't
|
|
6
|
+
* run other commands (`pub.duplicate()` is a good source).
|
|
7
|
+
*/
|
|
8
|
+
class IoRedisChannelTransport {
|
|
9
|
+
constructor(pub, sub) {
|
|
10
|
+
this.pub = pub;
|
|
11
|
+
this.sub = sub;
|
|
12
|
+
}
|
|
13
|
+
publish(channel, message) {
|
|
14
|
+
return this.pub.publish(channel, message);
|
|
15
|
+
}
|
|
16
|
+
async subscribe(channels, onMessage) {
|
|
17
|
+
if (!this.handler) {
|
|
18
|
+
this.handler = onMessage;
|
|
19
|
+
this.sub.on('message', (channel, message) => this.handler?.(channel, message));
|
|
20
|
+
}
|
|
21
|
+
if (channels.length)
|
|
22
|
+
await this.sub.subscribe(...channels);
|
|
23
|
+
}
|
|
24
|
+
async close() {
|
|
25
|
+
await this.sub.quit().catch(() => undefined);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
exports.IoRedisChannelTransport = IoRedisChannelTransport;
|
|
29
|
+
/** Single-process transport: delivery on the next tick. For tests and one-instance setups. */
|
|
30
|
+
class InMemoryChannelTransport {
|
|
31
|
+
constructor() {
|
|
32
|
+
this.subscribed = new Set();
|
|
33
|
+
this.published = [];
|
|
34
|
+
}
|
|
35
|
+
async publish(channel, message) {
|
|
36
|
+
this.published.push({ channel, message });
|
|
37
|
+
if (!this.subscribed.has(channel) || !this.handler)
|
|
38
|
+
return 0;
|
|
39
|
+
const handler = this.handler;
|
|
40
|
+
await new Promise((resolve) => setImmediate(() => {
|
|
41
|
+
handler(channel, message);
|
|
42
|
+
resolve();
|
|
43
|
+
}));
|
|
44
|
+
return 1;
|
|
45
|
+
}
|
|
46
|
+
async subscribe(channels, onMessage) {
|
|
47
|
+
this.handler = onMessage;
|
|
48
|
+
channels.forEach((c) => this.subscribed.add(c));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
exports.InMemoryChannelTransport = InMemoryChannelTransport;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { GlobalEventEnhancers } from '@my-nestjs-kit/events/pipeline';
|
|
2
|
+
import type { ChannelTransport } from './channel-transport';
|
|
3
|
+
export interface ChannelsModuleOptions extends GlobalEventEnhancers {
|
|
4
|
+
transport: ChannelTransport;
|
|
5
|
+
/** Identifies this instance in `message.from.serverId`. */
|
|
6
|
+
serverId: string;
|
|
7
|
+
/** Prepended to every channel name on the transport: `'channel'` → `channel:webhooks`. */
|
|
8
|
+
prefix?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface ChannelsModuleAsyncOptions {
|
|
11
|
+
imports?: any[];
|
|
12
|
+
inject?: any[];
|
|
13
|
+
useFactory: (...args: any[]) => ChannelsModuleOptions | Promise<ChannelsModuleOptions>;
|
|
14
|
+
}
|
|
15
|
+
export declare function toTransportChannel(prefix: string | undefined, channel: string): string;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.toTransportChannel = void 0;
|
|
4
|
+
function toTransportChannel(prefix, channel) {
|
|
5
|
+
return prefix ? `${prefix}:${channel}` : channel;
|
|
6
|
+
}
|
|
7
|
+
exports.toTransportChannel = toTransportChannel;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { ChannelsModuleOptions } from './channels-module.options';
|
|
2
|
+
import type { ChannelEventName, ChannelMessage, ChannelName, ChannelPayload, ChannelsMap, DefaultChannelsMap, PublishOptions } from './channels.types';
|
|
3
|
+
/** Typed publisher for every declared channel. */
|
|
4
|
+
export declare class ChannelsPublisher<M extends ChannelsMap = DefaultChannelsMap> {
|
|
5
|
+
private readonly options;
|
|
6
|
+
constructor(options: ChannelsModuleOptions);
|
|
7
|
+
publish<C extends ChannelName<M>, K extends ChannelEventName<C, M>>(channel: C, type: K, data: ChannelPayload<C, K, M>, opts?: PublishOptions): Promise<ChannelMessage<K, ChannelPayload<C, K, M>>>;
|
|
8
|
+
/** Publisher bound to one channel: `channels.of('webhooks').publish('send', cfg)`. */
|
|
9
|
+
of<C extends ChannelName<M>>(channel: C): {
|
|
10
|
+
publish: <K extends ChannelEventName<C, M>>(type: K, data: ChannelPayload<C, K, M>, opts?: PublishOptions) => Promise<ChannelMessage<K, ChannelPayload<C, K, M>>>;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.ChannelsPublisher = void 0;
|
|
16
|
+
const common_1 = require("@nestjs/common");
|
|
17
|
+
const channels_constants_1 = require("./channels.constants");
|
|
18
|
+
const channels_module_options_1 = require("./channels-module.options");
|
|
19
|
+
// TODO(kit): a per-channel publisher base — `ChannelPublisherBase<Channel>` with `emit()`/`message()`/`command()` by
|
|
20
|
+
// message type, subclassed per channel (`<name>.channel.ts`). Exists in webhooxy:
|
|
21
|
+
// packages/api/src/redis/base/redis-channel-pub.base.ts.
|
|
22
|
+
/** Typed publisher for every declared channel. */
|
|
23
|
+
let ChannelsPublisher = class ChannelsPublisher {
|
|
24
|
+
constructor(options) {
|
|
25
|
+
this.options = options;
|
|
26
|
+
}
|
|
27
|
+
async publish(channel, type, data, opts = {}) {
|
|
28
|
+
const message = {
|
|
29
|
+
channel,
|
|
30
|
+
type,
|
|
31
|
+
data,
|
|
32
|
+
from: { ...opts.from, serverId: this.options.serverId },
|
|
33
|
+
to: opts.to,
|
|
34
|
+
timestamp: Date.now(),
|
|
35
|
+
};
|
|
36
|
+
await this.options.transport.publish((0, channels_module_options_1.toTransportChannel)(this.options.prefix, channel), JSON.stringify(message));
|
|
37
|
+
return message;
|
|
38
|
+
}
|
|
39
|
+
/** Publisher bound to one channel: `channels.of('webhooks').publish('send', cfg)`. */
|
|
40
|
+
of(channel) {
|
|
41
|
+
return {
|
|
42
|
+
publish: (type, data, opts) => this.publish(channel, type, data, opts),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
exports.ChannelsPublisher = ChannelsPublisher;
|
|
47
|
+
exports.ChannelsPublisher = ChannelsPublisher = __decorate([
|
|
48
|
+
(0, common_1.Injectable)(),
|
|
49
|
+
__param(0, (0, common_1.Inject)(channels_constants_1.CHANNELS_MODULE_OPTIONS)),
|
|
50
|
+
__metadata("design:paramtypes", [Object])
|
|
51
|
+
], ChannelsPublisher);
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CHANNEL_ANY_EVENT = exports.CHANNEL_HANDLER_METADATA = exports.CHANNELS_MODULE_OPTIONS = void 0;
|
|
4
|
+
exports.CHANNELS_MODULE_OPTIONS = Symbol('CHANNELS_MODULE_OPTIONS');
|
|
5
|
+
exports.CHANNEL_HANDLER_METADATA = 'nest-kit:channel-handler';
|
|
6
|
+
exports.CHANNEL_ANY_EVENT = '*';
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { DynamicModule } from '@nestjs/common';
|
|
2
|
+
import type { ChannelsModuleAsyncOptions, ChannelsModuleOptions } from './channels-module.options';
|
|
3
|
+
/**
|
|
4
|
+
* Cross-instance pub/sub channels. Listeners are `@ChannelListener('<channel>')` providers
|
|
5
|
+
* (discovered, auto-subscribed); publishing goes through the typed `ChannelsPublisher`.
|
|
6
|
+
* Channels and their events are declared per module via `declare module '@my-nestjs-kit/channels'
|
|
7
|
+
* { interface DefaultChannelsMap { … } }`.
|
|
8
|
+
*/
|
|
9
|
+
export declare class ChannelsModule {
|
|
10
|
+
static forRoot(options: ChannelsModuleOptions): DynamicModule;
|
|
11
|
+
static forRootAsync(options: ChannelsModuleAsyncOptions): DynamicModule;
|
|
12
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var ChannelsModule_1;
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.ChannelsModule = void 0;
|
|
11
|
+
const common_1 = require("@nestjs/common");
|
|
12
|
+
const core_1 = require("@nestjs/core");
|
|
13
|
+
const channels_constants_1 = require("./channels.constants");
|
|
14
|
+
const channel_listeners_explorer_1 = require("./channel-listeners.explorer");
|
|
15
|
+
const channels_publisher_1 = require("./channels-publisher");
|
|
16
|
+
/**
|
|
17
|
+
* Cross-instance pub/sub channels. Listeners are `@ChannelListener('<channel>')` providers
|
|
18
|
+
* (discovered, auto-subscribed); publishing goes through the typed `ChannelsPublisher`.
|
|
19
|
+
* Channels and their events are declared per module via `declare module '@my-nestjs-kit/channels'
|
|
20
|
+
* { interface DefaultChannelsMap { … } }`.
|
|
21
|
+
*/
|
|
22
|
+
let ChannelsModule = ChannelsModule_1 = class ChannelsModule {
|
|
23
|
+
static forRoot(options) {
|
|
24
|
+
return ChannelsModule_1.forRootAsync({ useFactory: () => options });
|
|
25
|
+
}
|
|
26
|
+
static forRootAsync(options) {
|
|
27
|
+
return {
|
|
28
|
+
module: ChannelsModule_1,
|
|
29
|
+
global: true,
|
|
30
|
+
imports: [core_1.DiscoveryModule, ...(options.imports ?? [])],
|
|
31
|
+
providers: [
|
|
32
|
+
{
|
|
33
|
+
provide: channels_constants_1.CHANNELS_MODULE_OPTIONS,
|
|
34
|
+
useFactory: options.useFactory,
|
|
35
|
+
inject: options.inject ?? [],
|
|
36
|
+
},
|
|
37
|
+
channels_publisher_1.ChannelsPublisher,
|
|
38
|
+
channel_listeners_explorer_1.ChannelListenersExplorer,
|
|
39
|
+
],
|
|
40
|
+
exports: [channels_publisher_1.ChannelsPublisher],
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
exports.ChannelsModule = ChannelsModule;
|
|
45
|
+
exports.ChannelsModule = ChannelsModule = ChannelsModule_1 = __decorate([
|
|
46
|
+
(0, common_1.Module)({})
|
|
47
|
+
], ChannelsModule);
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The app's channels map — empty in the kit. Each module declares its channel next to its
|
|
3
|
+
* listener (no file lists every channel):
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* declare module '@my-nestjs-kit/channels' {
|
|
7
|
+
* interface DefaultChannelsMap {
|
|
8
|
+
* webhooks: { send: WebhookRequestConfig; process: WebhookRequestConfig };
|
|
9
|
+
* }
|
|
10
|
+
* }
|
|
11
|
+
* ```
|
|
12
|
+
* Key = channel name, value = its events: event name → `data` payload.
|
|
13
|
+
*/
|
|
14
|
+
export interface DefaultChannelsMap {
|
|
15
|
+
}
|
|
16
|
+
export type ChannelsMap = object;
|
|
17
|
+
export type ChannelName<M extends ChannelsMap = DefaultChannelsMap> = Extract<keyof M, string>;
|
|
18
|
+
export type ChannelEventName<C extends ChannelName<M>, M extends ChannelsMap = DefaultChannelsMap> = Extract<keyof M[C], string>;
|
|
19
|
+
/** Event names of every declared channel. */
|
|
20
|
+
export type AnyChannelEventName<M extends ChannelsMap = DefaultChannelsMap> = {
|
|
21
|
+
[C in ChannelName<M>]: ChannelEventName<C, M>;
|
|
22
|
+
}[ChannelName<M>];
|
|
23
|
+
export type ChannelPayload<C extends ChannelName<M>, K extends ChannelEventName<C, M>, M extends ChannelsMap = DefaultChannelsMap> = M[C][K];
|
|
24
|
+
export interface ChannelMember {
|
|
25
|
+
serverId?: string;
|
|
26
|
+
userId?: string;
|
|
27
|
+
clientId?: string;
|
|
28
|
+
}
|
|
29
|
+
/** What travels over the transport (JSON). */
|
|
30
|
+
export interface ChannelMessage<Type extends string = string, Data = unknown> {
|
|
31
|
+
channel: string;
|
|
32
|
+
type: Type;
|
|
33
|
+
data: Data;
|
|
34
|
+
from: ChannelMember;
|
|
35
|
+
to?: ChannelMember;
|
|
36
|
+
timestamp: number;
|
|
37
|
+
}
|
|
38
|
+
export interface PublishOptions {
|
|
39
|
+
to?: ChannelMember;
|
|
40
|
+
from?: Omit<ChannelMember, 'serverId'>;
|
|
41
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from './channels.types';
|
|
2
|
+
export * from './channel-transport';
|
|
3
|
+
export * from './channels-module.options';
|
|
4
|
+
export * from './channel-listener.decorator';
|
|
5
|
+
export * from './channels-publisher';
|
|
6
|
+
export * from './channel-listeners.explorer';
|
|
7
|
+
export * from './channels.module';
|
|
8
|
+
export { CHANNEL_ANY_EVENT } from './channels.constants';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.CHANNEL_ANY_EVENT = void 0;
|
|
18
|
+
__exportStar(require("./channels.types"), exports);
|
|
19
|
+
__exportStar(require("./channel-transport"), exports);
|
|
20
|
+
__exportStar(require("./channels-module.options"), exports);
|
|
21
|
+
__exportStar(require("./channel-listener.decorator"), exports);
|
|
22
|
+
__exportStar(require("./channels-publisher"), exports);
|
|
23
|
+
__exportStar(require("./channel-listeners.explorer"), exports);
|
|
24
|
+
__exportStar(require("./channels.module"), exports);
|
|
25
|
+
var channels_constants_1 = require("./channels.constants");
|
|
26
|
+
Object.defineProperty(exports, "CHANNEL_ANY_EVENT", { enumerable: true, get: function () { return channels_constants_1.CHANNEL_ANY_EVENT; } });
|
package/package.json
CHANGED
|
@@ -1,6 +1,93 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@my-nestjs-kit/channels",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0-dev.20261129020438",
|
|
4
|
+
"description": "Cross-instance pub/sub channels for NestJS: typed channel maps, ChannelsPublisher, @ChannelListener / @OnChannelEvent, ioredis or in-memory transport.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"nestjs",
|
|
7
|
+
"nest",
|
|
8
|
+
"pubsub",
|
|
9
|
+
"redis",
|
|
10
|
+
"channels",
|
|
11
|
+
"ioredis"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"homepage": "https://github.com/sabationok/my-nestjs-kit/tree/main/packages/channels#readme",
|
|
15
|
+
"bugs": {
|
|
16
|
+
"url": "https://github.com/sabationok/my-nestjs-kit/issues"
|
|
17
|
+
},
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/sabationok/my-nestjs-kit.git",
|
|
21
|
+
"directory": "packages/channels"
|
|
22
|
+
},
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=18"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"main": "dist/index.js",
|
|
30
|
+
"types": "dist/index.d.ts",
|
|
31
|
+
"exports": {
|
|
32
|
+
".": {
|
|
33
|
+
"types": "./dist/index.d.ts",
|
|
34
|
+
"require": "./dist/index.js",
|
|
35
|
+
"default": "./dist/index.js"
|
|
36
|
+
},
|
|
37
|
+
"./package.json": "./package.json"
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"dist",
|
|
41
|
+
"!dist/**/*.spec.*",
|
|
42
|
+
"!dist/**/*.tsbuildinfo",
|
|
43
|
+
"README.md",
|
|
44
|
+
"LICENSE"
|
|
45
|
+
],
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"@my-nestjs-kit/events": "^0.1.0-dev.20261129020438"
|
|
48
|
+
},
|
|
49
|
+
"peerDependencies": {
|
|
50
|
+
"@nestjs/common": "^10.4.1",
|
|
51
|
+
"@nestjs/core": "^10.4.1",
|
|
52
|
+
"ioredis": "^5.4.1",
|
|
53
|
+
"reflect-metadata": "^0.2.2"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@nestjs/common": "10.4.20",
|
|
57
|
+
"@nestjs/core": "10.4.1",
|
|
58
|
+
"@nestjs/testing": "10.4.1",
|
|
59
|
+
"@types/jest": "29.5.12",
|
|
60
|
+
"@types/node": "20.11.28",
|
|
61
|
+
"axios": "1.13.2",
|
|
62
|
+
"ioredis": "5.8.2",
|
|
63
|
+
"jest": "29.7.0",
|
|
64
|
+
"reflect-metadata": "0.2.2",
|
|
65
|
+
"rxjs": "7.8.1",
|
|
66
|
+
"ts-jest": "29.1.2",
|
|
67
|
+
"typescript": "5.4.2"
|
|
68
|
+
},
|
|
69
|
+
"jest": {
|
|
70
|
+
"moduleFileExtensions": [
|
|
71
|
+
"js",
|
|
72
|
+
"json",
|
|
73
|
+
"ts"
|
|
74
|
+
],
|
|
75
|
+
"rootDir": "src",
|
|
76
|
+
"testRegex": ".*\\.spec\\.ts$",
|
|
77
|
+
"transform": {
|
|
78
|
+
"^.+\\.ts$": [
|
|
79
|
+
"ts-jest",
|
|
80
|
+
{
|
|
81
|
+
"tsconfig": "<rootDir>/../tsconfig.spec.json"
|
|
82
|
+
}
|
|
83
|
+
]
|
|
84
|
+
},
|
|
85
|
+
"testEnvironment": "node"
|
|
86
|
+
},
|
|
87
|
+
"scripts": {
|
|
88
|
+
"build": "rm -rf dist && tsc -p tsconfig.json",
|
|
89
|
+
"build:watch": "tsc -p tsconfig.json --watch",
|
|
90
|
+
"typecheck": "tsc -p tsconfig.spec.json",
|
|
91
|
+
"test": "jest"
|
|
92
|
+
}
|
|
6
93
|
}
|