여기서 매핑은 하나의 값을 다른 값으로 대응시키는 것을 의미한다.
즉, 응답에 따라 값을 바꿔 대응시키는 것으로 생각했다.
즉, handle()
이 뭘 리턴하는지 알고 있지만 map()
을 이용하여 변이시킨다라는 것으로 본문을 이해했다.
예를 들어 handle()
에서 null
을 반환한다면 null
일 경우 다른 값을 반환시키는 그런 구조로 생각했다.
아래 코드로 더 이해해보자.
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
export interface Response<T> {
data: T;
}
@Injectable()
export class TransformInterceptor<T>
implements NestInterceptor<T, Response<T>> {
intercept(
context: ExecutionContext,
next: CallHandler
): Observable<Response<T>> {
return next.handle().pipe(map((data) => ({ data })));
}
}
catchError()
을 이용하여 예외를 재정의 하는데 사용할 수 있다.
import {
Injectable,
NestInterceptor,
ExecutionContext,
BadGatewayException,
CallHandler,
} from '@nestjs/common';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class ErrorsInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler):
Observable<any> {
return next
.handle()
.pipe(catchError((err) => throwError(new BadGatewayException())));
}
}
핸들러 호출을 차단 후 다른 값을 값을 반환해야할 때가 있다고 한다.
응답 시간 향상을 위해 cache를 구현하는 것인데,
이 때 사용할 수 있는 cache interceptor를 알아보자.
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { Observable, of } from 'rxjs';
@Injectable()
export class CacheInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler):
Observable<any> {
const isCached = true;
if (isCached) {
return of([]);
}
return next.handle();
}
}
캐시 인터셉터다. 이 코드에선 handler가 전혀 호출되지 않고, 엔드포인트를 호출한다면 응답이 바로 반환되는 방식이다.