import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor
} from '@nestjs/common'
import { Observable } from 'rxjs'
import { Response } from 'express'
/**
* Response Interceptor
* @class {ResponseInterceptor}
* @implements {NestInterceptor}
*/
@Injectable()
export class ResponseInterceptor implements NestInterceptor {
/**
* Intercept
* @param context {ExecutionContext} - 執行上下文
* @param next {CallHandler} - 呼叫處理程序
* @return {Observable} 返回 Observable
*/
intercept(context: ExecutionContext, next: CallHandler): Observable {
// 取得 Http 上下文
const contextHttp = context.switchToHttp()
// 取得 Response 物件
const response: Response = contextHttp.getResponse()
// 設定成Http Status 200
response.status(200)
return next.handle()
}
}
main.ts// 設定ResponseInterceptor
app.useGlobalInterceptors(new ResponseInterceptor())
Swagger
// 建立Swagger的文件
const document = NestSwaggerModule.createDocument(app, config)
// 修改所有Http method路徑的回應
Object.values(document.paths).forEach((path: any) => {
// 取得所有 HTTP 方法
const methods = Object.values(HttpMethodEnum).map((method) =>
method.toLowerCase()
)
methods.forEach((method) => {
// 取得 path[method] 的值
const pathMethod = path[method]
// pathMethod 存在
if (pathMethod) {
// 設定回應
pathMethod.responses = {
// HTTP 200
[HttpStatus.OK]: {
description: '一律使用HTTP 200',
content: {
'application/json': {
schema: apiResponseSchema
}
}
}
}
}
})
})