@nest-kr/request-storage
v0.0.10
Published
```cli npm i @nest-kr/request-storage ```
Downloads
32
Readme
Nest-kr/request-storage
This library for handling data per request. you can set and get data from storage which is maintained during the request scope. It uses cls-hooked internally and compatible with nest.js.
Installation
$ npm install --save @nest-kr/request-storage
How to use
Configure module
const app = await NestFactory.create(AppModule);
const requestStorage = app.get(RequestStorage);
app.use(RequestStorageMiddleware(requestStorage));
If you don't pass RequestStorage, RequestStorageMiddleware will create a new RequestStorage;
const app = await NestFactory.create(AppModule);
app.use(RequestStorageMiddleware());
Use RequestStorage
You can save a data and get the data from everywhere. data will be maintained during the request scope.
import { RequestStorage } from '@nest-kr/request-storage';
@Controller('users')
export class UserController {
constructor(private requestStorage: RequestStorage) {}
@Post('/')
async create() {
this.requestStorage.set('key', 'value');
...
}
}
...
import {Injectable} from '@nestjs/common';
import { Transaction } from '@nest-kr/transaction';
@Injectable()
export class UserService {
constructor(
private requestStorage: RequestStorage,
){}
async create(event: IntegrationEvent): Promise<void> {
...
const data = this.requestStorage.get('key');
...
}
}
Use RequestStorage with RequestInterceptor
Create RequestInterceptor
import { RequestInterceptor, RequestStorage } from '@nest-kr/request-storage';
export const AUTH_INFORMATION_KEY = 'AUTH_INFORMATION_KEY';
export class AuthInterceptor implements RequestInterceptor {
intercept(req: any, requestStorage: RequestStorage): void {
const headers = req.headers;
const userId: string = headers['user-id'] || '';
const userAgent: string = headers['user-agent'] || '';
requestStorage.set(AUTH_INFORMATION_KEY, {
userId,
userAgent
});
}
}
Add RequestInterceptor
const app = async NestFactory.create(AppModule);
const requestStorage = app.get(RequestStorage);
const authInterceptor = app.get(AuthInterceptor); // or new AuthInterceptor();
app.use(RequestStorageMiddleware(requestStorage, [authInterceptor]));
Use RequestStorage
@Injectable()
export class UserService {
constructor(
private requestStorage: RequestStorage,
){}
async handle(event: UserCreatedEvent): Promise<void> {
...
const {userID, userAgent} = this.requestStorage.get(AUTH_INFORMATION_KEY');
...
}
}