0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【NestJS】Responseデータの形式をInterceptorでいい感じに変換する方法

Last updated at Posted at 2022-03-21

概要

APIエンドポイントから返却されるレスポンスデータの形式をInterceptorで変換した

{
  "message": "success",
  "statusCode": 200,
  "errors": ""
}

Interceptorを定義する

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

// オブジェクトのexport
export const Info = {
    statusCode: 200,
    message: 'success'
}

/**
 * export type 型エイリアスのexport
 * オブジェクトの値のユニオン型を作成
 * typeof xxx &  型定義をマージして返却
 */
export type Response<T> = typeof Info & {
    data: T
}

/**
 * Object.assign で空オブジェクトに指定した形式で代入
 */
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> {
    intercept(context: ExecutionContext, next: CallHandler): Observable<Response<T>> {
        return next.handle().pipe(map(data => Object.assign({}, Info, {data})));
    }
}

定義したInterceptormain.tsで読み込む

コア関数NestFactoryを使用してNestアプリケーションのインスタンスを生成するアプリケーションのエントリファイルです。

The entry file of the application which uses the core function NestFactory to create a Nest application instance.

main.ts
async function bootstrap() {
    const app = await NestFactory.create(AppModule, {
        logger: loggerFactory.useFactory('warn'),
    })
    app.useGlobalInterceptors(new TransformInterceptor())
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?