@s1seven/nestjs-tools-async-local-storage
TypeScript icon, indicating that this package has built-in type declarations

0.2.2 • Public • Published

Async Local Storage`

npm

Installation

$ npm install --save @s1seven/nestjs-tools-async-local-storage

Usage

import assert from 'assert';
import { AsyncLocalStorage } from 'async_hooks';

// to provide type safety for the store map
declare module '@s1seven/nestjs-tools-async-local-storage' {
  interface RequestContext {
    type?: string;
  }
  interface ContextStoreProperties {
    id: number;
    username: string;
    profilePicture: string;
    name: string;
  }
}

import { AsyncLocalStorageService } from '@s1seven/nestjs-tools-async-local-storage';

const service = new AsyncLocalStorageService(new AsyncLocalStorage());

assert.throws(() => service.store.set('id', 1), new TypeError("Cannot read properties of undefined (reading 'set')"));
assert.throws(() => service.set('id', 1), new Error("Store is not initialized. Call 'enterWith' or 'run' first."));

service.enterWith(new Map());

// access store map directly
service.store.set('id', 1);
const id = service.store.get('id');
assert(typeof id === 'number');

// access store map via service which extends Map
service.set('username', 'john');
assert(typeof service.get('username') === 'string');

service.requestContext = { type: 'http' };
const requestContext = service.requestContext;
assert(typeof requestContext.type === 'string');

service.delete('username');

Readme

Keywords

none

Package Sidebar

Install

npm i @s1seven/nestjs-tools-async-local-storage

Weekly Downloads

3

Version

0.2.2

License

ISC

Unpacked Size

155 kB

Total Files

28

Last publish

Collaborators

  • christophbuehler
  • eamon0989
  • s1seven-service
  • stiebitzhofer