generated from streamich/tpl-ts-lib
-
-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: 🐛 make concurrency() decorator apply per class instance
- Loading branch information
Showing
3 changed files
with
66 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,22 @@ | ||
import {concurrency as _concurrency} from './concurrency'; | ||
|
||
const instances = new WeakMap<any, WeakMap<any, any>>(); | ||
|
||
/** | ||
* A class method decorator that limits the concurrency of the method to the | ||
* given number of parallel executions. All invocations are queued and executed | ||
* in the order they were called. | ||
*/ | ||
export function concurrency<This, Args extends any[], Return>(limit: number) { | ||
return ( | ||
target: (this: This, ...args: Args) => Promise<Return>, | ||
fn: (this: This, ...args: Args) => Promise<Return>, | ||
context?: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Promise<Return>>, | ||
) => { | ||
const limiter = _concurrency(limit); | ||
return async function (this: This, ...args: Args): Promise<Return> { | ||
return limiter(async () => await target.call(this, ...args)); | ||
let map = instances.get(this); | ||
if (!map) instances.set(this, map = new WeakMap<any, any>()); | ||
if (!map.has(fn)) map.set(fn, _concurrency(limit)); | ||
return map.get(fn)!(async () => await fn.call(this, ...args)); | ||
}; | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters