feat: als and prisma

This commit is contained in:
sauravdhakal12
2026-02-10 17:19:53 +05:45
parent 65480c4f8c
commit 9561693cb4
32 changed files with 2124 additions and 35 deletions

View File

@@ -0,0 +1,48 @@
import { Injectable } from '@nestjs/common';
import { AsyncLocalStorage } from 'async_hooks';
import { RequestContext } from './request-context.type';
@Injectable()
/**
* RequestContext holds per-request metadata including:
* - HTTP request
* - Auth payload (decoded JWT, optional)
* - Prisma transaction client (optional)
* - Correlation ID and other future cross-cutting concerns
*/
export class RequestContextService {
private readonly als = new AsyncLocalStorage<RequestContext>();
run(context: RequestContext, fn: () => void) {
this.als.run(context, fn);
}
get(): RequestContext {
const store = this.als.getStore();
if (!store) {
throw new Error('RequestContext not initialized');
}
return store;
}
set<K extends keyof RequestContext>(key: K, value: RequestContext[K]) {
this.get()[key] = value;
}
// Helpers
get user() {
return this.get().user;
}
get tx() {
return this.get().tx;
}
set tx(tx) {
this.set('tx', tx);
}
get isTransaction(): boolean {
return !!this.get().tx;
}
}