Added mutex + fixed rare duplicate chats bug + fixed connect bug

The mutex will prevent duplicate functions from being called and throwing funky errors.
This commit is contained in:
Adhiraj
2020-09-09 14:16:08 +05:30
parent 6e22ceac98
commit 6d2eaf93cb
11 changed files with 211 additions and 25 deletions

24
src/WAConnection/Mutex.ts Normal file
View File

@@ -0,0 +1,24 @@
/**
* A simple mutex that can be used as a decorator. For examples, see Tests.Mutex.ts
* @param keyGetter if you want to lock functions based on certain arguments, specify the key for the function based on the arguments
*/
export function Mutex (keyGetter?: (...args: any[]) => string) {
let tasks: { [k: string]: Promise<void> } = {}
return function (_, __, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value
descriptor.value = function (this: Object, ...args) {
const key = (keyGetter && keyGetter.call(this, ...args)) || 'undefined'
tasks[key] = (async () => {
try {
tasks[key] && await tasks[key]
} catch {
}
const result = await originalMethod.call(this, ...args)
return result
})()
return tasks[key]
}
}
}