@aitickets123654/common-kafka 1.0.6 → 1.0.8

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.
@@ -0,0 +1,17 @@
1
+ import { Kafka, Consumer, EachMessagePayload } from 'kafkajs';
2
+ import { Topics } from './topics';
3
+ interface Event {
4
+ topic: Topics;
5
+ data: any;
6
+ }
7
+ export declare abstract class Listener<T extends Event> {
8
+ abstract topic: T['topic'];
9
+ abstract groupId: string;
10
+ abstract onMessage(data: T['data'], payload: EachMessagePayload): void;
11
+ protected kafka: Kafka;
12
+ protected consumer: Consumer;
13
+ constructor(kafka: Kafka);
14
+ listen(): Promise<void>;
15
+ disconnect(): Promise<void>;
16
+ }
17
+ export {};
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Listener = void 0;
4
+ class Listener {
5
+ constructor(kafka) {
6
+ this.kafka = kafka;
7
+ }
8
+ async listen() {
9
+ this.consumer = this.kafka.consumer({ groupId: this.groupId });
10
+ await this.consumer.connect();
11
+ console.log(`Listener connected to Kafka (${this.topic})`);
12
+ await this.consumer.subscribe({
13
+ topic: this.topic,
14
+ fromBeginning: true,
15
+ });
16
+ await this.consumer.run({
17
+ autoCommit: false,
18
+ eachMessage: async (payload) => {
19
+ var _a;
20
+ const { message } = payload;
21
+ const value = (_a = message.value) === null || _a === void 0 ? void 0 : _a.toString();
22
+ if (!value)
23
+ return;
24
+ try {
25
+ const data = JSON.parse(value);
26
+ await this.onMessage(data, payload);
27
+ await this.consumer.commitOffsets([
28
+ {
29
+ topic: payload.topic,
30
+ partition: payload.partition,
31
+ offset: (Number(message.offset) + 1).toString(),
32
+ },
33
+ ]);
34
+ }
35
+ catch (err) {
36
+ console.error(`Error processing message:`, err);
37
+ }
38
+ },
39
+ });
40
+ }
41
+ async disconnect() {
42
+ if (this.consumer) {
43
+ await this.consumer.disconnect();
44
+ console.log(`Disconnected listener (${this.topic})`);
45
+ }
46
+ }
47
+ }
48
+ exports.Listener = Listener;
@@ -0,0 +1,18 @@
1
+ import { Kafka, Producer, Admin } from 'kafkajs';
2
+ import { Topics } from './topics';
3
+ interface Event {
4
+ topic: Topics;
5
+ data: any;
6
+ }
7
+ export declare abstract class Publisher<T extends Event> {
8
+ abstract topic: T['topic'];
9
+ protected kafka: Kafka;
10
+ protected producer: Producer;
11
+ protected admin: Admin;
12
+ constructor(kafka: Kafka);
13
+ connect(): Promise<void>;
14
+ disconnect(): Promise<void>;
15
+ private ensureTopicExists;
16
+ publish(data: T['data']): Promise<void>;
17
+ }
18
+ export {};
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Publisher = void 0;
4
+ class Publisher {
5
+ constructor(kafka) {
6
+ this.kafka = kafka;
7
+ this.producer = kafka.producer();
8
+ this.admin = kafka.admin();
9
+ }
10
+ async connect() {
11
+ await this.admin.connect();
12
+ await this.ensureTopicExists();
13
+ await this.producer.connect();
14
+ console.log(`Publisher connected to Kafka and topic '${this.topic}' ready`);
15
+ }
16
+ async disconnect() {
17
+ await this.producer.disconnect();
18
+ await this.admin.disconnect();
19
+ console.log('Kafka publisher disconnected');
20
+ }
21
+ async ensureTopicExists() {
22
+ try {
23
+ const topics = await this.admin.listTopics();
24
+ if (!topics.includes(this.topic)) {
25
+ await this.admin.createTopics({
26
+ topics: [
27
+ {
28
+ topic: this.topic,
29
+ numPartitions: 2,
30
+ replicationFactor: 1,
31
+ },
32
+ ],
33
+ waitForLeaders: true,
34
+ validateOnly: false,
35
+ timeout: 5000,
36
+ });
37
+ console.log(`Topic '${this.topic}' created successfully.`);
38
+ }
39
+ else {
40
+ console.log(`Topic '${this.topic}' already exists.`);
41
+ }
42
+ }
43
+ catch (err) {
44
+ console.error(`Failed to ensure topic '${this.topic}':`, err);
45
+ throw err;
46
+ }
47
+ }
48
+ async publish(data) {
49
+ try {
50
+ await this.producer.send({
51
+ topic: this.topic,
52
+ messages: [{ value: JSON.stringify(data) }],
53
+ });
54
+ console.log(`Event published to topic '${this.topic}'`);
55
+ }
56
+ catch (err) {
57
+ console.error('Failed to publish event:', err);
58
+ throw err;
59
+ }
60
+ }
61
+ }
62
+ exports.Publisher = Publisher;
@@ -0,0 +1,10 @@
1
+ import { Topics } from './topics';
2
+ export interface TicketCreatedEvent {
3
+ topic: Topics.TicketCreated;
4
+ data: {
5
+ id: string;
6
+ title: string;
7
+ price: number;
8
+ userId: string;
9
+ };
10
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,10 @@
1
+ import { Topics } from './topics';
2
+ export interface TicketUpdatedEvent {
3
+ topic: Topics.TicketUpdated;
4
+ data: {
5
+ id: string;
6
+ title: string;
7
+ price: number;
8
+ userId: string;
9
+ };
10
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,4 @@
1
+ export declare enum Topics {
2
+ TicketCreated = "ticket-created3",
3
+ TicketUpdated = "ticket-updated3"
4
+ }
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Topics = void 0;
4
+ var Topics;
5
+ (function (Topics) {
6
+ Topics["TicketCreated"] = "ticket-created3";
7
+ Topics["TicketUpdated"] = "ticket-updated3";
8
+ })(Topics || (exports.Topics = Topics = {}));
package/build/index.d.ts CHANGED
@@ -8,3 +8,8 @@ export * from './middlewares/current-user';
8
8
  export * from './middlewares/error-handler';
9
9
  export * from './middlewares/require-auth';
10
10
  export * from './middlewares/validate-request';
11
+ export * from './events/base-listener';
12
+ export * from './events/base-publisher';
13
+ export * from './events/topics';
14
+ export * from './events/ticket-created-event';
15
+ export * from './events/ticket-updated-event';
package/build/index.js CHANGED
@@ -24,3 +24,8 @@ __exportStar(require("./middlewares/current-user"), exports);
24
24
  __exportStar(require("./middlewares/error-handler"), exports);
25
25
  __exportStar(require("./middlewares/require-auth"), exports);
26
26
  __exportStar(require("./middlewares/validate-request"), exports);
27
+ __exportStar(require("./events/base-listener"), exports);
28
+ __exportStar(require("./events/base-publisher"), exports);
29
+ __exportStar(require("./events/topics"), exports);
30
+ __exportStar(require("./events/ticket-created-event"), exports);
31
+ __exportStar(require("./events/ticket-updated-event"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aitickets123654/common-kafka",
3
- "version": "1.0.6",
3
+ "version": "1.0.8",
4
4
  "description": "",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
@@ -26,6 +26,7 @@
26
26
  "cookie-session": "^2.1.0",
27
27
  "express": "^4.17.1",
28
28
  "express-validator": "^6.4.0",
29
- "jsonwebtoken": "^9.0.2"
29
+ "jsonwebtoken": "^9.0.2",
30
+ "kafkajs": "^2.2.4"
30
31
  }
31
32
  }