Skip to content

Commit

Permalink
refactor: extract build req / res context
Browse files Browse the repository at this point in the history
  • Loading branch information
MiffyLiye committed Jan 16, 2024
1 parent da3112b commit 93a573a
Showing 1 changed file with 25 additions and 12 deletions.
37 changes: 25 additions & 12 deletions src/logger.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,22 +25,15 @@ export class RequestInterceptor implements NestInterceptor {
next: CallHandler<any>,
): Observable<any> | Promise<Observable<any>> {
const start = new Date();
let req: Express.Request;
let res: ServerResponse | undefined;
if (context.getType() === 'http') {
const ctx = context.switchToHttp();
req = ctx.getRequest<Express.Request>();
res = ctx.getResponse<ServerResponse>();
} else if (context.getType<GqlContextType>() === 'graphql') {
const ctx = GqlExecutionContext.create(context).getContext();
req = ctx.req;
} else {
const ctx = buildContext(context);
if (!ctx) {
return next.handle();
}
const { req, res } = ctx;

const method = req.method;
const url = req.originalUrl;
const route = context.getType() === 'http' ? req.route.path : req.baseUrl;
const route = req?.route?.path || req.baseUrl;

const options = this.options;
const reqId = options.genReqId
Expand Down Expand Up @@ -95,7 +88,7 @@ export class RequestInterceptor implements NestInterceptor {
this._logger.info({
...common,
'short-body': body && buildShortBody(body, options.shortBodyLength),
'status-code': context.getType() === 'http' ? res.statusCode : 200,
'status-code': res.statusCode,
});
};
return next
Expand All @@ -104,6 +97,26 @@ export class RequestInterceptor implements NestInterceptor {
}
}

function buildContext(
context: ExecutionContext,
): { req: Express.Request; res: ServerResponse } | undefined {
if (context.getType() === 'http') {
const ctx = context.switchToHttp();
return {
req: ctx.getRequest<Express.Request>(),
res: ctx.getResponse<ServerResponse>(),
};
} else if (context.getType<GqlContextType>() === 'graphql') {
const ctx = GqlExecutionContext.create(context).getContext();
return {
req: ctx.req,
res: ctx.req.res,
};
} else {
return undefined;
}
}

function buildShortBody(raw, length = 500) {
return util
.inspect(raw, { depth: 3, maxStringLength: 50 })
Expand Down

0 comments on commit 93a573a

Please sign in to comment.