高瀬博道の技術ブログ

高瀬博道の技術ブログです。

もう2023年になったので、今さらNestJSに入門しようと思う - その18

前回

takasehiromichiex.com

nullを除外するインターセプタ

null値が出現するたびに、空の文字列に変換するインターセプタを作成します。

$ nest g interceptor interceptor/excludeNull

以下のファイルが作成されました。

src/interceptor/exclude-null/exclude-null.interceptor.ts
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class ExcludeNullInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle();
  }
}
src/interceptor/exclude-null/exclude-null.logging.spec.ts
import { ExcludeNullInterceptor } from './exclude-null.interceptor';

describe('ExcludeNullInterceptor', () => {
  it('should be defined', () => {
    expect(new ExcludeNullInterceptor()).toBeDefined();
  });
});

インターセプタを修正します。

src/interceptor/exclude-null/exclude-null.interceptor.ts
import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from "@nestjs/common";
import { map, Observable } from "rxjs";

@Injectable()
export class ExcludeNullInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(map((value) => (value === null ? "" : value)));
  }
}

これで、nullが空の文字列に変換されるインターセプタができました。

例外マッピングするインターセプタ

スローされた例外をオーバーライドするインターセプタを作成します。

$ nest g interceptor interceptor/errors

以下のファイルが作成されました。

src/interceptor/errors/errors.interceptor.ts
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class ErrorsInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle();
  }
}
src/interceptor/errors/errors.logging.spec.ts
import { ErrorsInterceptor } from './errors.interceptor';

describe('ErrorsInterceptor', () => {
  it('should be defined', () => {
    expect(new ErrorsInterceptor()).toBeDefined();
  });
});

インターセプタを修正します。

src/interceptor/exclude-null/exclude-null.interceptor.ts
import {
  BadGatewayException,
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from "@nestjs/common";
import { catchError, Observable, throwError } from "rxjs";

@Injectable()
export class ErrorsInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next
      .handle()
      .pipe(catchError((error) => throwError(() => new BadGatewayException())));
  }
}

これで、スローされた例外をオーバーライドするインターセプタができました。

まとめ

ここまでで、

  • nullを除外するインターセプタ
  • 例外マッピングするインターセプタ

について学びました。

次回は、カスタムデコレータについて掘り下げようと思います。

コード

今回のコードは、以下に格納しました。

github.com

takasehiromichiex.com