feat: Basic setup with auth
This commit is contained in:
0
common/interceptors/index.ts
Normal file
0
common/interceptors/index.ts
Normal file
72
common/interceptors/response.interceptor.ts
Normal file
72
common/interceptors/response.interceptor.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import {
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
ExecutionContext,
|
||||
CallHandler,
|
||||
} from '@nestjs/common';
|
||||
import { DataResponse, MessageResponse } from 'common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
|
||||
@Injectable()
|
||||
export class ResponseInterceptor<T> implements NestInterceptor<T, any> {
|
||||
intercept(_: ExecutionContext, next: CallHandler): Observable<any> {
|
||||
return next.handle().pipe(
|
||||
map((data) => {
|
||||
if (data instanceof MessageResponse) return data;
|
||||
else if (data instanceof DataResponse) return data;
|
||||
else if (typeof data === 'string') return new MessageResponse(data);
|
||||
return new DataResponse(data);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/* NOTE: How to access request
|
||||
*
|
||||
@Injectable()
|
||||
export class ResponseInterceptor<T> implements NestInterceptor<T, any> {
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
|
||||
const req = context.switchToHttp().getRequest();
|
||||
req.userId = 'ram';
|
||||
return next.handle();
|
||||
// return next.handle().pipe(
|
||||
// map((data) => {
|
||||
// if (data instanceof MessageResponse) return data;
|
||||
// else if (data instanceof DataResponse) return data;
|
||||
// else if (typeof data === 'string') return new MessageResponse(data);
|
||||
// return new DataResponse(data);
|
||||
// }),
|
||||
// );
|
||||
}
|
||||
}
|
||||
|
||||
REQUEST
|
||||
↓
|
||||
Guards
|
||||
↓
|
||||
Interceptors (before)
|
||||
↓
|
||||
Pipes
|
||||
↓
|
||||
Controller method
|
||||
↓
|
||||
Interceptors (after) ← YOU ARE HERE
|
||||
↓
|
||||
Response
|
||||
|
||||
|
||||
3️⃣ What is next.handle() really?
|
||||
next.handle(): Observable<T>
|
||||
|
||||
|
||||
This is:
|
||||
|
||||
An RxJS stream of whatever the controller returns
|
||||
|
||||
Not the request
|
||||
|
||||
Not the response object
|
||||
|
||||
Just the return value
|
||||
* */
|
||||
Reference in New Issue
Block a user