Skip to content

Commit 04fa32a

Browse files
committed
feat(redisio): allow background savings when an error handler is set
1 parent 811a668 commit 04fa32a

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

storages/redisio/src/redisio.storage.ts

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@ export class RedisIOStorage
1313
} = { maxAge: 86400 }
1414
) {}
1515

16+
private errorHandler: ((error: Error) => void) | undefined;
17+
18+
onError(listener: (error: Error) => void) {
19+
this.errorHandler = listener;
20+
}
21+
1622
async getItems<T>(keys: string[]): Promise<{ [key: string]: T | undefined }> {
1723
const res = Object.fromEntries(
1824
(await this.redis().mget(...keys)).map((entry, i) => {
@@ -50,7 +56,14 @@ export class RedisIOStorage
5056
redisPipeline.set(val.key, JSON.stringify(val.content));
5157
}
5258
});
53-
await redisPipeline.exec();
59+
const savePromise = redisPipeline.exec();
60+
61+
if (this.errorHandler) {
62+
// if we have an error handler, we do not need to await the result
63+
savePromise.catch(err => this.errorHandler && this.errorHandler(err));
64+
} else {
65+
await savePromise
66+
}
5467
}
5568

5669
public async getItem<T>(key: string): Promise<T | undefined> {
@@ -80,10 +93,17 @@ export class RedisIOStorage
8093
return;
8194
}
8295
const ttl = options?.ttl ?? this.options?.maxAge;
96+
let savePromise: Promise<any>;
8397
if (ttl) {
84-
await this.redis().setex(key, ttl, content);
98+
savePromise = this.redis().setex(key, ttl, content);
99+
} else {
100+
savePromise = this.redis().set(key, content);
101+
}
102+
if (this.errorHandler) {
103+
// if we have an error handler, we do not need to await the result
104+
savePromise.catch(err => this.errorHandler && this.errorHandler(err));
85105
} else {
86-
await this.redis().set(key, content);
106+
await savePromise
87107
}
88108
}
89109

0 commit comments

Comments
 (0)