feat: als and prisma
This commit is contained in:
48
core/als/request-context.service.ts
Normal file
48
core/als/request-context.service.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user