This repository has been archived on 2021-06-02. You can view files and clone it, but cannot push or open issues or pull requests.
RealtimeDB-OLD/src/database/lock.ts

30 lines
732 B
TypeScript

export type Release = { release: () => void };
export default class DocumentLock {
private locks = new Map<string, (() => void)[]>();
getLocks() {
return Array.from(this.locks.keys());
}
async lock(collection: string = "", document: string = "") {
//TODO: Check collection locks
let key = collection + "/" + document;
let l = this.locks.get(key);
if (l)
await new Promise<void>((resolve) => {
l.push(resolve);
this.locks.set(key, l);
});
else {
l = [];
this.locks.set(key, l);
}
return () => {
if (l.length > 0) setImmediate(() => l.shift()());
else this.locks.delete(key);
};
}
}