0.2.1 • Published 5 years ago

@renanhangai/nestjs-context v0.2.1

Weekly downloads
1
License
MIT
Repository
gitlab
Last release
5 years ago

nestjs-context

Generate a context for every request on nestjs

By using interceptors, this library can help you setup a new context object for every request to manage things like transactions and custom data per request without using the Request Scope

Usage

Create the interceptor

import { Injectable } from "@nestjs/common";
import {
	RequestContext,
	RequestContextInterceptor,
	RequestMiddlewareState,
	RequestContextMiddlewareNextCallback,
} from "@renanhangai/nestjs-context";

export interface ContextType {
	dbConnection: Connection;
}

/// Re-export the decorator
export { RequestContext };

/// Export the interceptor
@Injectable()
export class MyContextInterceptor extends RequestContextInterceptor<ContextType> {
	/// The middleware
	middlewares() {
		return [
			this.middlewareTransaction,
		],
	}
	/// Apply the middleware for the transaction
	async middlewareTransaction(
		state: RequestMiddlewareState<ContextType>,
		next: any
	) {
		await this.database.transaction( (connection) => {
			state.context.dbConnection = connection;
			await next();
			state.context.dbConnection = null;
		});
	}
}

Use it on your application

import { Module } from "@nestjs/common";
import { APP_INTERCEPTOR } from "@nestjs/core";
import { MyContextInterceptor } from "./somewhere";

@Module({
	proviers: [
		{
			provide: APP_INTERCEPTOR,
			useClass: MyContextInterceptor,
		},
	],
})
class AppModule {}
0.2.1

5 years ago

0.2.0

5 years ago

0.1.0

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago