@uber-clone/common 1.0.2 → 1.0.4

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,20 @@
1
+ export declare class KafkaClient {
2
+ private kafka;
3
+ private producer;
4
+ private consumer;
5
+ private admin;
6
+ private isConnected;
7
+ private config;
8
+ constructor();
9
+ private getKafkaConfig;
10
+ connect(): Promise<void>;
11
+ private ensureTopics;
12
+ publish(topic: string, event: any): Promise<void>;
13
+ subscribe(topic: string, handler: (event: any) => Promise<void>, options?: {
14
+ fromBeginning?: boolean;
15
+ }): Promise<void>;
16
+ private ensureConnection;
17
+ disconnect(): Promise<void>;
18
+ healthCheck(): Promise<boolean>;
19
+ getConnectionStatus(): boolean;
20
+ }
@@ -0,0 +1,231 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.KafkaClient = void 0;
13
+ const kafkajs_1 = require("kafkajs");
14
+ class KafkaClient {
15
+ constructor() {
16
+ this.isConnected = false;
17
+ this.config = this.getKafkaConfig();
18
+ this.kafka = new kafkajs_1.Kafka({
19
+ clientId: this.config.clientId,
20
+ brokers: this.config.brokers,
21
+ logLevel: kafkajs_1.logLevel.ERROR,
22
+ retry: {
23
+ initialRetryTime: this.config.initialRetryTime,
24
+ retries: this.config.retries,
25
+ },
26
+ connectionTimeout: 30000,
27
+ requestTimeout: 30000,
28
+ });
29
+ this.producer = this.kafka.producer({
30
+ allowAutoTopicCreation: this.config.enableAutoTopicCreation,
31
+ transactionTimeout: this.config.transactionTimeout,
32
+ maxInFlightRequests: 1,
33
+ idempotent: true,
34
+ });
35
+ this.consumer = this.kafka.consumer({
36
+ groupId: this.config.consumerGroup,
37
+ sessionTimeout: this.config.sessionTimeout,
38
+ heartbeatInterval: this.config.heartbeatInterval,
39
+ allowAutoTopicCreation: this.config.enableAutoTopicCreation,
40
+ });
41
+ this.admin = this.kafka.admin();
42
+ }
43
+ getKafkaConfig() {
44
+ return {
45
+ clientId: process.env.KAFKA_CLIENT_ID || "uber-service",
46
+ brokers: (process.env.KAFKA_BROKERS || "localhost:9092")
47
+ .split(",")
48
+ .map((b) => b.trim()),
49
+ consumerGroup: process.env.KAFKA_CONSUMER_GROUP || "uber-group",
50
+ enableAutoTopicCreation: process.env.KAFKA_AUTO_TOPIC_CREATION === "true",
51
+ sessionTimeout: parseInt(process.env.KAFKA_SESSION_TIMEOUT || "30000"),
52
+ heartbeatInterval: parseInt(process.env.KAFKA_HEARTBEAT_INTERVAL || "10000"),
53
+ transactionTimeout: parseInt(process.env.KAFKA_TRANSACTION_TIMEOUT || "30000"),
54
+ retries: parseInt(process.env.KAFKA_RETRIES || "8"),
55
+ initialRetryTime: parseInt(process.env.KAFKA_INITIAL_RETRY_TIME || "100"),
56
+ };
57
+ }
58
+ connect() {
59
+ return __awaiter(this, void 0, void 0, function* () {
60
+ if (this.isConnected)
61
+ return;
62
+ console.log(`Connecting to Kafka with brokers: ${this.config.brokers.join(", ")}`);
63
+ try {
64
+ yield this.producer.connect();
65
+ yield this.consumer.connect();
66
+ yield this.admin.connect();
67
+ this.isConnected = true;
68
+ console.log("Successfully connected to Kafka");
69
+ }
70
+ catch (error) {
71
+ console.error("Failed to connect to Kafka:", error);
72
+ throw new Error(`Kafka connection failed: ${error instanceof Error ? error.message : "Unknown error"}`);
73
+ }
74
+ yield this.ensureTopics();
75
+ });
76
+ }
77
+ ensureTopics() {
78
+ return __awaiter(this, void 0, void 0, function* () {
79
+ const topics = [
80
+ { topic: "user-events", partitions: 3, replicationFactor: 1 },
81
+ { topic: "auth-events", partitions: 3, replicationFactor: 1 },
82
+ { topic: "ride-requests", partitions: 6, replicationFactor: 1 },
83
+ { topic: "driver-assignments", partitions: 6, replicationFactor: 1 },
84
+ { topic: "location-updates", partitions: 12, replicationFactor: 1 },
85
+ { topic: "payment-events", partitions: 4, replicationFactor: 1 },
86
+ { topic: "notification-events", partitions: 4, replicationFactor: 1 },
87
+ { topic: "ticket-events", partitions: 3, replicationFactor: 1 },
88
+ { topic: "order-events", partitions: 6, replicationFactor: 1 },
89
+ ];
90
+ try {
91
+ const existingTopics = yield this.admin.listTopics();
92
+ const topicsToCreate = topics.filter((t) => !existingTopics.includes(t.topic));
93
+ if (topicsToCreate.length > 0) {
94
+ console.log(`Creating Kafka topics: ${topicsToCreate
95
+ .map((t) => t.topic)
96
+ .join(", ")}`);
97
+ yield this.admin.createTopics({
98
+ topics: topicsToCreate,
99
+ waitForLeaders: true,
100
+ });
101
+ console.log(`Successfully created topics: ${topicsToCreate
102
+ .map((t) => t.topic)
103
+ .join(", ")}`);
104
+ }
105
+ else {
106
+ console.log("All required Kafka topics already exist");
107
+ }
108
+ }
109
+ catch (error) {
110
+ console.error("Error creating topics:", error);
111
+ throw new Error(`Failed to create Kafka topics: ${error instanceof Error ? error.message : "Unknown error"}`);
112
+ }
113
+ });
114
+ }
115
+ publish(topic, event) {
116
+ return __awaiter(this, void 0, void 0, function* () {
117
+ yield this.ensureConnection();
118
+ if (!event || typeof event !== "object") {
119
+ throw new Error("Event must be a valid object");
120
+ }
121
+ try {
122
+ const message = {
123
+ topic,
124
+ messages: [
125
+ {
126
+ key: event.correlationId || event.eventId || event.id || "default-key",
127
+ value: JSON.stringify(event),
128
+ headers: {
129
+ "event-type": event.type || "unknown",
130
+ source: event.source || "unknown-service",
131
+ timestamp: event.timestamp
132
+ ? event.timestamp.toISOString()
133
+ : new Date().toISOString(),
134
+ version: event.version ? event.version.toString() : "1.0",
135
+ },
136
+ },
137
+ ],
138
+ };
139
+ const result = yield this.producer.send(message);
140
+ console.log(`Published event to topic ${topic}:`, {
141
+ partition: result[0].partition,
142
+ offset: result[0].baseOffset,
143
+ eventType: event.type,
144
+ });
145
+ }
146
+ catch (error) {
147
+ console.error(`Failed to publish event to ${topic}:`, error);
148
+ throw new Error(`Failed to publish event to ${topic}: ${error instanceof Error ? error.message : "Unknown error"}`);
149
+ }
150
+ });
151
+ }
152
+ subscribe(topic, handler, options) {
153
+ return __awaiter(this, void 0, void 0, function* () {
154
+ yield this.ensureConnection();
155
+ try {
156
+ yield this.consumer.subscribe({
157
+ topic,
158
+ fromBeginning: (options === null || options === void 0 ? void 0 : options.fromBeginning) || false,
159
+ });
160
+ console.log(`Subscribed to topic: ${topic}`);
161
+ yield this.consumer.run({
162
+ eachMessage: (_a) => __awaiter(this, [_a], void 0, function* ({ topic, partition, message }) {
163
+ try {
164
+ if (!message.value) {
165
+ console.warn(`Received message with no value from ${topic}:${partition}`);
166
+ return;
167
+ }
168
+ const event = JSON.parse(message.value.toString());
169
+ console.log(`Received event from ${topic}:${partition}`, {
170
+ offset: message.offset,
171
+ eventType: event.type || "unknown",
172
+ });
173
+ yield handler(event);
174
+ }
175
+ catch (error) {
176
+ console.error(`Error processing message from ${topic}:${partition}:`, error);
177
+ // In production, you might want to implement dead letter queue or retry logic here
178
+ }
179
+ }),
180
+ });
181
+ }
182
+ catch (error) {
183
+ console.error(`Failed to subscribe to topic ${topic}:`, error);
184
+ throw new Error(`Failed to subscribe to topic ${topic}: ${error instanceof Error ? error.message : "Unknown error"}`);
185
+ }
186
+ });
187
+ }
188
+ ensureConnection() {
189
+ return __awaiter(this, void 0, void 0, function* () {
190
+ if (!this.isConnected) {
191
+ yield this.connect();
192
+ }
193
+ });
194
+ }
195
+ disconnect() {
196
+ return __awaiter(this, void 0, void 0, function* () {
197
+ try {
198
+ if (this.isConnected) {
199
+ yield Promise.allSettled([
200
+ this.producer.disconnect(),
201
+ this.consumer.disconnect(),
202
+ this.admin.disconnect(),
203
+ ]);
204
+ this.isConnected = false;
205
+ console.log("Disconnected from Kafka");
206
+ }
207
+ }
208
+ catch (error) {
209
+ console.error("Error disconnecting from Kafka:", error);
210
+ }
211
+ });
212
+ }
213
+ // Health check method
214
+ healthCheck() {
215
+ return __awaiter(this, void 0, void 0, function* () {
216
+ try {
217
+ yield this.admin.describeCluster();
218
+ return this.isConnected;
219
+ }
220
+ catch (error) {
221
+ console.error("Kafka health check failed:", error);
222
+ return false;
223
+ }
224
+ });
225
+ }
226
+ // Get connection status
227
+ getConnectionStatus() {
228
+ return this.isConnected;
229
+ }
230
+ }
231
+ exports.KafkaClient = KafkaClient;
@@ -0,0 +1,34 @@
1
+ import { Kafka, EachMessagePayload } from "kafkajs";
2
+ import { Subjects } from "./subjects";
3
+ interface Event {
4
+ subject: Subjects;
5
+ data: any;
6
+ }
7
+ /**
8
+ * Abstract class for a Kafka Consumer (Listener).
9
+ * It abstracts away Kafka connection, topic subscription, and message parsing.
10
+ * The equivalent of NATS 'queueGroupName' is the Kafka 'groupId'.
11
+ */
12
+ export declare abstract class KafkaListener<T extends Event> {
13
+ abstract subject: T["subject"];
14
+ abstract groupId: string;
15
+ abstract onMessage(data: T["data"], messagePayload: EachMessagePayload): void;
16
+ private kafka;
17
+ private consumer;
18
+ constructor(kafka: Kafka);
19
+ /**
20
+ * Connects the consumer and subscribes to the topic.
21
+ * FIX: The consumer is now initialized here, where 'this.groupId' is guaranteed to be set
22
+ * by the subclass constructor before the 'listen()' method is called.
23
+ */
24
+ listen(): Promise<void>;
25
+ /**
26
+ * Converts the message value (Buffer) into a parsed JSON object.
27
+ */
28
+ private parseMessage;
29
+ /**
30
+ * Graceful shutdown function.
31
+ */
32
+ close(): Promise<void>;
33
+ }
34
+ export {};
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.KafkaListener = void 0;
13
+ /**
14
+ * Abstract class for a Kafka Consumer (Listener).
15
+ * It abstracts away Kafka connection, topic subscription, and message parsing.
16
+ * The equivalent of NATS 'queueGroupName' is the Kafka 'groupId'.
17
+ */
18
+ class KafkaListener {
19
+ // No changes needed here, as it only stores the Kafka client instance.
20
+ constructor(kafka) {
21
+ this.kafka = kafka;
22
+ }
23
+ /**
24
+ * Connects the consumer and subscribes to the topic.
25
+ * FIX: The consumer is now initialized here, where 'this.groupId' is guaranteed to be set
26
+ * by the subclass constructor before the 'listen()' method is called.
27
+ */
28
+ listen() {
29
+ return __awaiter(this, void 0, void 0, function* () {
30
+ try {
31
+ // Initialize the consumer instance using the abstract 'groupId'
32
+ this.consumer = this.kafka.consumer({ groupId: this.groupId });
33
+ yield this.consumer.connect();
34
+ // Subscribe to the defined topic
35
+ yield this.consumer.subscribe({
36
+ topic: this.subject,
37
+ fromBeginning: true, // Similar to NATS setDeliverAllAvailable
38
+ });
39
+ console.log(`Kafka Consumer connected and listening to topic: ${this.subject} with group: ${this.groupId}`);
40
+ // Run the consumer to process messages
41
+ yield this.consumer.run({
42
+ eachMessage: (payload) => __awaiter(this, void 0, void 0, function* () {
43
+ const { topic, partition, message } = payload;
44
+ console.log(`Message received: ${topic} / partition ${partition}`);
45
+ // Kafka data is always a Buffer or null, so we must parse it.
46
+ const parsedData = this.parseMessage(message.value);
47
+ // Pass the parsed data and the full payload to the implementation
48
+ this.onMessage(parsedData, payload);
49
+ // Note: Offset is automatically committed by kafkajs
50
+ // after onMessage completes successfully.
51
+ }),
52
+ });
53
+ }
54
+ catch (err) {
55
+ console.error("Kafka Listener Error:", err);
56
+ // Exit or retry connection logic would go here
57
+ }
58
+ });
59
+ }
60
+ /**
61
+ * Converts the message value (Buffer) into a parsed JSON object.
62
+ */
63
+ parseMessage(value) {
64
+ if (!value) {
65
+ console.warn("Received null message value. Returning empty object.");
66
+ return {};
67
+ }
68
+ try {
69
+ return JSON.parse(value.toString("utf8"));
70
+ }
71
+ catch (e) {
72
+ console.error("Failed to parse Kafka message value.", e);
73
+ throw new Error("Invalid message format received from Kafka.");
74
+ }
75
+ }
76
+ /**
77
+ * Graceful shutdown function.
78
+ */
79
+ close() {
80
+ return __awaiter(this, void 0, void 0, function* () {
81
+ // Only try to disconnect if the consumer was actually initialized
82
+ if (this.consumer) {
83
+ yield this.consumer.disconnect();
84
+ console.log(`Kafka Consumer for group ${this.groupId} disconnected.`);
85
+ }
86
+ });
87
+ }
88
+ }
89
+ exports.KafkaListener = KafkaListener;
@@ -0,0 +1,28 @@
1
+ import { Kafka } from "kafkajs";
2
+ import { Subjects } from "./subjects";
3
+ interface Event {
4
+ subject: Subjects;
5
+ data: any;
6
+ }
7
+ /**
8
+ * Abstract class for a Kafka Producer (Publisher).
9
+ * It abstracts away Kafka connection and message serialization.
10
+ */
11
+ export declare abstract class KafkaPublisher<T extends Event> {
12
+ abstract subject: T["subject"];
13
+ private producer;
14
+ constructor(kafka: Kafka);
15
+ /**
16
+ * Connects the producer to the Kafka broker. Call this before publishing.
17
+ */
18
+ connect(): Promise<void>;
19
+ /**
20
+ * Publishes the event data to the defined topic.
21
+ */
22
+ publish(data: T["data"]): Promise<void>;
23
+ /**
24
+ * Graceful shutdown function.
25
+ */
26
+ close(): Promise<void>;
27
+ }
28
+ export {};
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.KafkaPublisher = void 0;
13
+ /**
14
+ * Abstract class for a Kafka Producer (Publisher).
15
+ * It abstracts away Kafka connection and message serialization.
16
+ */
17
+ class KafkaPublisher {
18
+ constructor(kafka) {
19
+ // Create a producer instance
20
+ this.producer = kafka.producer();
21
+ }
22
+ /**
23
+ * Connects the producer to the Kafka broker. Call this before publishing.
24
+ */
25
+ connect() {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ yield this.producer.connect();
28
+ console.log("Kafka Producer connected.");
29
+ });
30
+ }
31
+ /**
32
+ * Publishes the event data to the defined topic.
33
+ */
34
+ publish(data) {
35
+ return __awaiter(this, void 0, void 0, function* () {
36
+ // Ensure the producer is connected before sending
37
+ // In a real app, you'd manage connection state better.
38
+ // Assuming connect() was called before this method.
39
+ try {
40
+ const response = yield this.producer.send({
41
+ topic: this.subject,
42
+ messages: [
43
+ {
44
+ value: JSON.stringify(data), // Kafka requires data to be a Buffer or string
45
+ // key: 'some-key-for-partitioning' // Use a key for ordered processing (e.g., ticket ID)
46
+ },
47
+ ],
48
+ });
49
+ console.log("Event published to subject", this.subject, "Response:", response);
50
+ }
51
+ catch (err) {
52
+ console.error("Kafka Publisher Error:", err);
53
+ throw err;
54
+ }
55
+ });
56
+ }
57
+ /**
58
+ * Graceful shutdown function.
59
+ */
60
+ close() {
61
+ return __awaiter(this, void 0, void 0, function* () {
62
+ yield this.producer.disconnect();
63
+ console.log("Kafka Producer disconnected.");
64
+ });
65
+ }
66
+ }
67
+ exports.KafkaPublisher = KafkaPublisher;
@@ -0,0 +1,28 @@
1
+ export declare enum Subjects {
2
+ UserCreated = "user.created",
3
+ UserUpdated = "user.updated",
4
+ UserDeleted = "user.deleted",
5
+ UserProfileUpdated = "user.profile-updated",
6
+ UserSignedIn = "user.signed-in",
7
+ UserSignedOut = "user.signed-out",
8
+ UserPasswordChanged = "user.password-changed",
9
+ UserAccountLocked = "user.account-locked",
10
+ RideRequested = "ride.requested",
11
+ RideAccepted = "ride.accepted",
12
+ RideStarted = "ride.started",
13
+ RideCompleted = "ride.completed",
14
+ RideCancelled = "ride.cancelled",
15
+ DriverOnline = "driver.online",
16
+ DriverOffline = "driver.offline",
17
+ DriverLocationUpdated = "driver.location-updated",
18
+ DriverRideAccepted = "driver.ride-accepted",
19
+ DriverRideCompleted = "driver.ride-completed",
20
+ PaymentInitiated = "payment.initiated",
21
+ PaymentCompleted = "payment.completed",
22
+ PaymentFailed = "payment.failed",
23
+ PaymentRefunded = "payment.refunded",
24
+ NotificationEmail = "notification.email",
25
+ NotificationSMS = "notification.sms",
26
+ NotificationPush = "notification.push",
27
+ NotificationInApp = "notification.in-app"
28
+ }
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Subjects = void 0;
4
+ // Subjects enum
5
+ var Subjects;
6
+ (function (Subjects) {
7
+ // User events
8
+ Subjects["UserCreated"] = "user.created";
9
+ Subjects["UserUpdated"] = "user.updated";
10
+ Subjects["UserDeleted"] = "user.deleted";
11
+ Subjects["UserProfileUpdated"] = "user.profile-updated";
12
+ // Auth events
13
+ Subjects["UserSignedIn"] = "user.signed-in";
14
+ Subjects["UserSignedOut"] = "user.signed-out";
15
+ Subjects["UserPasswordChanged"] = "user.password-changed";
16
+ Subjects["UserAccountLocked"] = "user.account-locked";
17
+ // Ride events
18
+ Subjects["RideRequested"] = "ride.requested";
19
+ Subjects["RideAccepted"] = "ride.accepted";
20
+ Subjects["RideStarted"] = "ride.started";
21
+ Subjects["RideCompleted"] = "ride.completed";
22
+ Subjects["RideCancelled"] = "ride.cancelled";
23
+ // Driver events
24
+ Subjects["DriverOnline"] = "driver.online";
25
+ Subjects["DriverOffline"] = "driver.offline";
26
+ Subjects["DriverLocationUpdated"] = "driver.location-updated";
27
+ Subjects["DriverRideAccepted"] = "driver.ride-accepted";
28
+ Subjects["DriverRideCompleted"] = "driver.ride-completed";
29
+ // Payment events
30
+ Subjects["PaymentInitiated"] = "payment.initiated";
31
+ Subjects["PaymentCompleted"] = "payment.completed";
32
+ Subjects["PaymentFailed"] = "payment.failed";
33
+ Subjects["PaymentRefunded"] = "payment.refunded";
34
+ // Notification events
35
+ Subjects["NotificationEmail"] = "notification.email";
36
+ Subjects["NotificationSMS"] = "notification.sms";
37
+ Subjects["NotificationPush"] = "notification.push";
38
+ Subjects["NotificationInApp"] = "notification.in-app";
39
+ })(Subjects || (exports.Subjects = Subjects = {}));
@@ -0,0 +1,88 @@
1
+ import { Subjects } from "./subjects";
2
+ export interface BaseEvent {
3
+ type: Subjects;
4
+ source: string;
5
+ timestamp: Date;
6
+ version: string;
7
+ data: any;
8
+ correlationId?: string;
9
+ eventId?: string;
10
+ id?: string;
11
+ }
12
+ export interface UserEvent extends BaseEvent {
13
+ type: Subjects.UserCreated | Subjects.UserUpdated | Subjects.UserDeleted | Subjects.UserProfileUpdated;
14
+ data: {
15
+ userId: string;
16
+ email: string;
17
+ name?: string;
18
+ phone?: string;
19
+ [key: string]: any;
20
+ };
21
+ }
22
+ export interface AuthEvent extends BaseEvent {
23
+ type: Subjects.UserSignedIn | Subjects.UserSignedOut | Subjects.UserPasswordChanged | Subjects.UserAccountLocked;
24
+ data: {
25
+ userId: string;
26
+ email: string;
27
+ ipAddress?: string;
28
+ userAgent?: string;
29
+ [key: string]: any;
30
+ };
31
+ }
32
+ export interface RideEvent extends BaseEvent {
33
+ type: Subjects.RideRequested | Subjects.RideAccepted | Subjects.RideStarted | Subjects.RideCompleted | Subjects.RideCancelled;
34
+ data: {
35
+ rideId: string;
36
+ passengerId: string;
37
+ driverId?: string;
38
+ pickupLocation: {
39
+ lat: number;
40
+ lng: number;
41
+ address?: string;
42
+ };
43
+ destinationLocation: {
44
+ lat: number;
45
+ lng: number;
46
+ address?: string;
47
+ };
48
+ estimatedFare?: number;
49
+ [key: string]: any;
50
+ };
51
+ }
52
+ export interface DriverEvent extends BaseEvent {
53
+ type: Subjects.DriverOnline | Subjects.DriverOffline | Subjects.DriverLocationUpdated | Subjects.DriverRideAccepted | Subjects.DriverRideCompleted;
54
+ data: {
55
+ driverId: string;
56
+ location?: {
57
+ lat: number;
58
+ lng: number;
59
+ };
60
+ rideId?: string;
61
+ [key: string]: any;
62
+ };
63
+ }
64
+ export interface PaymentEvent extends BaseEvent {
65
+ type: Subjects.PaymentInitiated | Subjects.PaymentCompleted | Subjects.PaymentFailed | Subjects.PaymentRefunded;
66
+ data: {
67
+ paymentId: string;
68
+ userId: string;
69
+ rideId?: string;
70
+ amount: number;
71
+ currency: string;
72
+ paymentMethod: string;
73
+ status: string;
74
+ [key: string]: any;
75
+ };
76
+ }
77
+ export interface NotificationEvent extends BaseEvent {
78
+ type: Subjects.NotificationEmail | Subjects.NotificationSMS | Subjects.NotificationPush | Subjects.NotificationInApp;
79
+ data: {
80
+ userId: string;
81
+ notificationType: string;
82
+ title: string;
83
+ message: string;
84
+ metadata?: any;
85
+ [key: string]: any;
86
+ };
87
+ }
88
+ export type UberEvent = UserEvent | AuthEvent | RideEvent | DriverEvent | PaymentEvent | NotificationEvent;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/build/index.d.ts CHANGED
@@ -8,3 +8,6 @@ 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/kafka-client";
12
+ export * from "./events/types";
13
+ export * from "./events/subjects";
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
+ // export * from "./events/kafka-listener";
28
+ // export * from "./events/kafka-publisher";
29
+ __exportStar(require("./events/kafka-client"), exports);
30
+ __exportStar(require("./events/types"), exports);
31
+ __exportStar(require("./events/subjects"), exports);
@@ -12,7 +12,6 @@ const currentUser = (req, res, next) => {
12
12
  }
13
13
  try {
14
14
  const payload = jsonwebtoken_1.default.verify(req.session.jwt, process.env.JWT_KEY);
15
- console.log("[payload]", payload);
16
15
  req.currentUser = payload;
17
16
  }
18
17
  catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uber-clone/common",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "main": "./build/index.js",
5
5
  "types": "./build/index.d.ts",
6
6
  "files": [
@@ -27,6 +27,7 @@
27
27
  "express": "^5.1.0",
28
28
  "express-validator": "^7.2.1",
29
29
  "jsonwebtoken": "^9.0.2",
30
+ "kafkajs": "^2.2.4",
30
31
  "node-nats-streaming": "^0.3.2"
31
32
  }
32
33
  }