Skip to content

Commit cc1651d

Browse files
Luna-Runatamimaj
and
tamimaj
authored
Refact: Apply strict mode (#16)
* Refact: Apply strict mode modify type errors that occur when the strict is set to true * Fix: TS strict mode errors. * Refactor: Updated tests. * v1.0.5 --------- Co-authored-by: tamimaj <[email protected]>
1 parent cd53544 commit cc1651d

13 files changed

+150
-83
lines changed

examples/client-app/package-lock.json

+3-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples/users-microservice/package-lock.json

+3-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

lib/redis-stream-client.core-module.ts

+12-7
Original file line numberDiff line numberDiff line change
@@ -57,14 +57,13 @@ export class RedisStreamClientCoreModule {
5757
);
5858
}
5959

60-
if (options.useExisting || options.useFactory) {
61-
return [this.createAsyncClientProvider(options)];
60+
const providers: Provider[] = [this.createAsyncClientProvider(options)];
61+
62+
if (!options.useExisting && !options.useFactory && options.useClass) {
63+
providers.push({ provide: options.useClass, useClass: options.useClass });
6264
}
6365

64-
return [
65-
this.createAsyncClientProvider(options),
66-
{ provide: options.useClass, useClass: options.useClass },
67-
];
66+
return providers
6867
}
6968

7069
/* createAsyncOptionsProvider */
@@ -86,12 +85,18 @@ export class RedisStreamClientCoreModule {
8685
};
8786
}
8887

88+
const inject = options.useClass
89+
? [options.useClass]
90+
: options.useExisting
91+
? [options.useExisting]
92+
: []
93+
8994
return {
9095
provide: REDIS_STREAM_CLIENT_MODULE_OPTIONS,
9196
useFactory: async (
9297
optionsFactory: RedisStreamClientModuleOptionsFactory,
9398
) => optionsFactory.createRedisStreamClientModuleOptions(),
94-
inject: [options.useClass || options.useExisting],
99+
inject,
95100
};
96101
}
97102
}

lib/redis.client.ts

+19-11
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@ import { firstValueFrom, share } from 'rxjs';
1212
export class RedisStreamClient extends ClientProxy {
1313
protected readonly logger = new Logger(RedisStreamClient.name);
1414

15-
private redis: RedisInstance; // server instance for listening on response streams.
15+
private redis: RedisInstance | null = null; // server instance for listening on response streams.
1616

17-
private client: RedisInstance; // client instance for publishing streams.
17+
private client: RedisInstance | null = null; // client instance for publishing streams.
1818

19-
protected connection: Promise<any>; // client connection logic is required by framework.
19+
protected connection: Promise<any> | null = null; // client connection logic is required by framework.
2020

2121
private streamsToListenOn: string[] = []; // response streams to listen on.
2222

@@ -40,9 +40,9 @@ export class RedisStreamClient extends ClientProxy {
4040
this.logger.log(
4141
'Redis Client Responses Listener connected successfully on ' +
4242
(this.options.connection?.url ??
43-
this.options.connection.host +
43+
this.options.connection?.host +
4444
':' +
45-
this.options.connection.port),
45+
this.options.connection?.port),
4646
);
4747

4848
this.initListener();
@@ -102,6 +102,8 @@ export class RedisStreamClient extends ClientProxy {
102102

103103
public async handleXadd(stream: string, serializedPayloadArray: any[]) {
104104
try {
105+
if (!this.client) throw new Error('Redis client instance not found.');
106+
105107
let response = await this.client.xadd(
106108
stream,
107109
'*',
@@ -222,12 +224,14 @@ export class RedisStreamClient extends ClientProxy {
222224

223225
private async createConsumerGroup(stream: string, consumerGroup: string) {
224226
try {
227+
if (!this.redis) throw new Error('Redis instance not found.');
228+
225229
await this.redis.xgroup('CREATE', stream, consumerGroup, '$', 'MKSTREAM');
226230

227231
return true;
228232
} catch (error) {
229233
// if group exist for this stream. log debug.
230-
if (error?.message.includes('BUSYGROUP')) {
234+
if (error instanceof Error && error?.message.includes('BUSYGROUP')) {
231235
this.logger.debug(
232236
'Consumer Group "' +
233237
consumerGroup +
@@ -242,14 +246,16 @@ export class RedisStreamClient extends ClientProxy {
242246
}
243247
}
244248

245-
private async listenOnStreams() {
249+
private async listenOnStreams(): Promise<void> {
246250
try {
251+
if (!this.redis) throw new Error('Redis instance not found.');
252+
247253
let results: any[];
248254

249255
results = await this.redis.xreadgroup(
250256
'GROUP',
251-
this.options?.streams?.consumerGroup || undefined,
252-
this.options?.streams?.consumer || undefined, // need to make it throw an error.
257+
this.options?.streams?.consumerGroup || '',
258+
this.options?.streams?.consumer || '',
253259
'BLOCK',
254260
this.options?.streams?.block || 0,
255261
'STREAMS',
@@ -315,8 +321,8 @@ export class RedisStreamClient extends ClientProxy {
315321

316322
// after message
317323
private async deliverToHandler(
318-
correlationId,
319-
parsedPayload,
324+
correlationId: string,
325+
parsedPayload: any,
320326
ctx: RedisStreamContext,
321327
) {
322328
try {
@@ -369,6 +375,8 @@ export class RedisStreamClient extends ClientProxy {
369375

370376
private async handleAck(inboundContext: RedisStreamContext) {
371377
try {
378+
if (!this.client) throw new Error('Redis client instance not found.');
379+
372380
await this.client.xack(
373381
inboundContext.getStream(),
374382
inboundContext.getConsumerGroup(),

lib/redis.server.ts

+20-10
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,11 @@ export class RedisStreamStrategy
1717
extends Server
1818
implements CustomTransportStrategy
1919
{
20-
private streamHandlerMap = {};
20+
private streamHandlerMap: { [key: string]: any } = {};
2121

22-
private redis: RedisInstance;
22+
private redis: RedisInstance | null = null;
2323

24-
private client: RedisInstance;
24+
private client: RedisInstance | null = null;
2525

2626
constructor(private readonly options: ConstructorOptions) {
2727
super();
@@ -40,7 +40,9 @@ export class RedisStreamStrategy
4040
this.logger.log(
4141
'Redis connected successfully on ' +
4242
(this.options.connection?.url ??
43-
this.options.connection.host + ':' + this.options.connection.port),
43+
this.options.connection?.host +
44+
':' +
45+
this.options.connection?.port),
4446
);
4547

4648
this.bindHandlers();
@@ -85,20 +87,22 @@ export class RedisStreamStrategy
8587
return true;
8688
} catch (error) {
8789
// JSON.parse will throw error, if is not parsable.
88-
this.logger.debug(error + '. Handler Pattern is: ' + pattern);
90+
this.logger.debug!(error + '. Handler Pattern is: ' + pattern);
8991
return false;
9092
}
9193
}
9294

9395
private async createConsumerGroup(stream: string, consumerGroup: string) {
9496
try {
97+
if (!this.redis) throw new Error('Redis instance not found.');
98+
9599
await this.redis.xgroup('CREATE', stream, consumerGroup, '$', 'MKSTREAM');
96100

97101
return true;
98102
} catch (error) {
99103
// if group exist for this stream. log debug.
100-
if (error?.message.includes('BUSYGROUP')) {
101-
this.logger.debug(
104+
if (error instanceof Error && error.message.includes('BUSYGROUP')) {
105+
this.logger.debug!(
102106
'Consumer Group "' +
103107
consumerGroup +
104108
'" already exists for stream: ' +
@@ -134,6 +138,8 @@ export class RedisStreamStrategy
134138
);
135139
}
136140

141+
if (!this.client) throw new Error('Redis client instance not found.');
142+
137143
await this.client.xadd(responseObj.stream, '*', ...serializedEntries);
138144
}),
139145
);
@@ -147,6 +153,8 @@ export class RedisStreamStrategy
147153

148154
private async handleAck(inboundContext: RedisStreamContext) {
149155
try {
156+
if (!this.client) throw new Error('Redis client instance not found.');
157+
150158
await this.client.xack(
151159
inboundContext.getStream(),
152160
inboundContext.getConsumerGroup(),
@@ -248,14 +256,16 @@ export class RedisStreamStrategy
248256
}
249257
}
250258

251-
private async listenOnStreams() {
259+
private async listenOnStreams(): Promise<void> {
252260
try {
261+
if (!this.redis) throw new Error('Redis instance not found.');
262+
253263
let results: any[];
254264

255265
results = await this.redis.xreadgroup(
256266
'GROUP',
257-
this.options?.streams?.consumerGroup || undefined,
258-
this.options?.streams?.consumer || undefined, // need to make it throw an error.
267+
this.options?.streams?.consumerGroup || '',
268+
this.options?.streams?.consumer || '',
259269
'BLOCK',
260270
this.options?.streams?.block || 0,
261271
'STREAMS',

lib/redis.utils.ts

+1-2
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,9 @@ export function createRedisConnection(
66
connection?: RedisConnectionOptions,
77
): RedisInstance {
88
// connection obj is optional, ioredis handle the default connection to localhost:6379
9-
109
if (connection?.url) {
1110
return new Redis(connection?.url, connection);
1211
} else {
13-
return new Redis(connection);
12+
return new Redis(connection!);
1413
}
1514
}

lib/requests-map.ts

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
1-
export class RequestsMap<T, S> {
2-
private map = {};
1+
export class RequestsMap<T extends string | number | symbol, S> {
2+
private map: Record<T, S> = {} as Record<T, S>;
33

44
constructor() {}
55

6-
public addEntry(requestId, handler) {
6+
public addEntry(requestId: T, handler: S) {
77
this.map[requestId] = handler;
88
return true;
99
}
1010

11-
public getEntry(requestId) {
11+
public getEntry(requestId: T) {
1212
return this.map[requestId];
1313
}
1414

15-
public removeEntry(requestId) {
15+
public removeEntry(requestId: T) {
1616
delete this.map[requestId];
1717
return true;
1818
}

lib/streams.utils.ts

+6-6
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ export async function serialize(
4444
return stringifiedResponse;
4545
} catch (error) {
4646
logger.error(error);
47-
return null;
47+
return [];
4848
}
4949
}
5050

@@ -58,10 +58,10 @@ export async function parseJson(data: string): Promise<any> {
5858
}
5959
}
6060

61-
export function parseRawMessage(rawMessage: any): any {
61+
export function parseRawMessage(rawMessage: any): Record<string, any> {
6262
let payload = rawMessage[1];
6363

64-
let obj = {};
64+
let obj: Record<string, any> = {};
6565

6666
for (let i = 0; i < payload.length; i += 2) {
6767
obj[payload[i]] = payload[i + 1];
@@ -70,9 +70,9 @@ export function parseRawMessage(rawMessage: any): any {
7070
return obj;
7171
}
7272

73-
export function stringifyMessage(messageObj: any): any {
73+
export function stringifyMessage(messageObj: Record<string, string>): string[] {
7474
try {
75-
let finalArray = [];
75+
let finalArray: string[] = [];
7676

7777
for (let key in messageObj) {
7878
finalArray.push(key);
@@ -82,7 +82,7 @@ export function stringifyMessage(messageObj: any): any {
8282
return finalArray;
8383
} catch (error) {
8484
logger.error(error);
85-
return null;
85+
return [];
8686
}
8787
}
8888

0 commit comments

Comments
 (0)