A Proxy-based lightweight library to add Continuation-Local Storage aka (CLS) to class contructor, method calls, getters and setters.
-
Install libraries
npm i cls-class-proxy cls-hooked
-
Install typings if you use typescript
npm i -D @types/cls-hooked
-
Set in your tsconfig.json
"experimentalDecorators": true, "emitDecoratorMetadata": true
-
In your code
import { getNamespace } from 'cls-hooked' import { proxify, CLS_CLASS_PROXY_NAMESPACE_NAME } from 'cls-class-proxy' @proxify() class Example { constructor() { const namespace = getNamespace(CLS_CLASS_PROXY_NAMESPACE_NAME) // At this point the namespace has an active contex (namspace.active returns the context) // You can set and get data for the context } method1() { const namespace = getNamespace(CLS_CLASS_PROXY_NAMESPACE_NAME) // At this point the namespace has an active contex (namspace.active returns the context) // You can set and get data for the context } get prop1() { const namespace = getNamespace(CLS_CLASS_PROXY_NAMESPACE_NAME) // At this point the namespace has an active contex (namspace.active returns the context) // You can set and get data for the context } set prop2() { const namespace = getNamespace(CLS_CLASS_PROXY_NAMESPACE_NAME) // At this point the namespace has an active contex (namspace.active returns the context) // You can set and get data for the context } }
import { getNamespace } from 'cls-hooked'
import { proxify, CLS_CLASS_PROXY_NAMESPACE_NAME } from 'cls-class-proxy'
class Example {}
const ExampleProxified = proxify()(Example)
proxify
accepts an optional object with options:
namespace
: string - custom namespace name to use instead of default CLS_CLASS_PROXY_NAMESPACE_NAMEcache
: boolean - to wrap method, getter and setter calls in a CLS contextcls-class-proxy
recursively looks up property descriptors on a target object and its prototype chain. To avoid doing that for every callcls-class-proxy
caches property descriptors in a Map. It's enabled by default.