A Thread-local storage (TLS) like Map implementation, base on node async hooks, support nodejs & typescript
-
thread local support for nodejs & typescript
-
named scope & chain support , easily to get closest forefather scope
-
browser or lower version of node if provided an async-hooks implementation with constructor
tips
- .get(key: K) will find the key recursive
- A scope can have multiple names
- Top scope is named 'root' by default
install
npm install async-hooks-storage
import
const { AsyncHookMap } = require('async-hooks-storage')
Usage
typescript:
import { AsyncHookMap } from 'async-hooks-storage'
const scope = new AsyncHookMap()
Promise.resolve().then(() => {
scope.set('aa', 'first')
scope.alias('ccc')
assert.equal(scope.get('aa'), 'first')
return Promise.resolve().then(() => {
assert(scope.has('aa'), 'should has the key')
assert(!scope.has('not'), 'should not has the key')
assert(!scope.has('aa', false), 'should not has the key in this scope')
assert.equal(scope.get('aa'), 'first')
scope.set('aa', 'second')
assert.equal(scope.get('aa'), 'second')
}).then(() => {
assert.equal(scope.get('aa'), 'second')
assert.equal(scope.parent('ccc').get('aa'), 'first')
assert.equal(scope.parent('root').get('aa'), 'first')
scope.parent().delete('aa')
assert.equal(scope.get('aa'), 'first')
scope.parent('ccc').set('bb', 'bb')
assert.equal(scope.get('bb'), 'bb')
scope.delete('bb')
assert.equal(scope.get('bb'), 'bb')
})
})
})
Api:
class AsyncHookMap<K = any, V = any> {
constructor(asyncHooks?: any);
desctroy(): void;
executionAsyncId(): number;
alias(name: string): this;
hasName(name: string): boolean | undefined;
parent(name?: string): AsyncScope<K, V>;
closest(name: string): AsyncScope<K, V>;
get(key: K): V | undefined;
has(key: K, recursion?: boolean): boolean;
set(key: K, value: V): this;
delete(key: K): boolean;
clear(): void;
}