Seamless asynchronous local storage management using the NodeJS Async Local Storage. This package is designed as a core component for the gedai
project (currently supported by the lootup
project), and offers plug-and-play functionality, empowering developers to effortlessly integrate asynchronous local storage into their applications.
This package was originally developed by gedai, however he stopped maintaining it and so this fork was created. This repo may have improvements/changes in the future.
Install the necessary packages with your favorite Package Manager.
$ npm install @lootupteam/nestjs-core
In your app.module.ts
import ContextModule
and set it up.
// app.module.ts
import { ContextModule } from '@lootupteam/nestjs-core';
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [
// Setup Context Module Here
ContextModule.forRoot({}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
In main.ts
import the apply the required configuration with configureContextWrapper
.
// main.ts
import { configureContextWrappers } from '@lootupteam/nestjs-core';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule)
// Setup Context Wrappers Here
.then(configureContextWrappers);
await app.listen(3000);
}
bootstrap();
In your services, add ContextService
as an injectable dependency.
// app.service.ts
import { ContextService } from '@lootupteam/nestjs-core';
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
// Injected here
constructor(private readonly context: ContextService) {}
getHello(): string {
// Recover any previously set property
const contextId = this.context.getId();
return `[${contextId}]: Hello World!`;
}
}
Implementing continuation passing style introduces complexity to systems. While it's a viable method for data sharing across layers and components, exercising caution is paramount. It's remarkably easy to lose oversight of stored data within the context, potentially leading to bugs or leaks.
- Tracking Execution Context: Utilize to share a traceId throughout the request lifecycle, facilitating seamless monitoring and debugging.
- Automatically Managing Database Transactions: Implement for streamlined transaction handling, ensuring data integrity and consistency. Ability to handle the transactions without touching the business layers.
- Tracking Tenant Shard ID: Employ for efficient tracking and management of tenant-specific data shards, enhancing multi-tenancy support and scalability without having to pass properties everywhere in your code.
@lootupteam/nestjscore is MIT licensed.