Add locks to different write operations

This commit is contained in:
Ajay
2023-07-23 23:21:50 -04:00
parent b2081fe155
commit 8bcc781da7
5 changed files with 68 additions and 3 deletions

37
src/utils/redisLock.ts Normal file
View File

@@ -0,0 +1,37 @@
import redis from "../utils/redis";
import { Logger } from "./logger";
const defaultTimeout = 5000;
export type AcquiredLock = {
status: false
} | {
status: true;
unlock: () => void;
};
export async function acquireLock(key: string, timeout = defaultTimeout): Promise<AcquiredLock> {
try {
const result = await redis.set(key, "1", {
PX: timeout,
NX: true
});
if (result) {
return {
status: true,
unlock: () => void redis.del(key).catch((err) => Logger.error(err))
};
} else {
return {
status: false
};
}
} catch (e) {
Logger.error(e as string);
}
return {
status: false
};
}