fix(logger): displat proper response time
MODIFY
packages/middleware-logger/src/index.ts
packages/middleware-logger/src/index.ts
import { Effect, HttpRequest } from '@marblejs/core';
import chalk from 'chalk';
import { tap } from 'rxjs/operators';
+import { TimeFactory } from './time.factory';
const getStatusCode = (statusCode: number): string =>
statusCode >= 400
? chalk.yellow(statusCode.toString())
: chalk.green(statusCode.toString());
-const getEndTime = (hrStartTime: [number, number]): number => {
- const hrEndTime = process.hrtime(hrStartTime)[1] / 1000000;
- return Math.round(hrEndTime * 100) / 100;
-};
-
const printLog = (
method: string,
url: string,
statusCode: string,
- endTime: number
+ formattedTime: string
) => {
- console.info(`%s %s %s %dms`, method, url, statusCode, endTime);
+ console.info(`%s %s %s %s`, method, url, statusCode, formattedTime);
};
export const logger$: Effect<HttpRequest> = (request$, response) =>
request$.pipe(
tap(request => {
- const startTime = process.hrtime();
+ const startTime = new Date();
response.on('finish', () =>
printLog(
request.method!,
request.url!,
getStatusCode(response.statusCode),
- getEndTime(startTime)
+ TimeFactory.formatTime(TimeFactory.getTimeDifferenceMs(startTime))
)
);
})

ADD
packages/middleware-logger/src/time.factory.spec.ts
+import { TimeFactory } from './time.factory';
+
+describe('TimeFactory', () => {
+
+ test('#formatTime formats time to miliseconds or seconds', () => {
+ // given
+ const moreThanSecond = 1200;
+ const lessThanSecond = 800;
+
+ // when
+ const formattedSecond = TimeFactory.formatTime(moreThanSecond);
+ const formattedMilisecond = TimeFactory.formatTime(lessThanSecond);
+
+ // then
+ expect(formattedSecond).toBe('1.2s');
+ expect(formattedMilisecond).toBe('800ms');
+ });
+
+ test('#getTimeDifferenceMs returns time difference in miliseconds', () => {
+ // given
+ const startTime = new Date(1000);
+ spyOn(global, 'Date').and.returnValue({ getTime: () => 2000 });
+
+ // when
+ const timeDifference = TimeFactory.getTimeDifferenceMs(startTime);
+
+ // then
+ expect(timeDifference).toBe(2000 - 1000);
+ });
+
+});

ADD
packages/middleware-logger/src/time.factory.ts
+export namespace TimeFactory {
+
+ export const formatTime = (timeMs: number) =>
+ timeMs > 1000
+ ? `${timeMs / 1000}s`
+ : `${timeMs}ms`;
+
+ export const getTimeDifferenceMs = (startTime: Date): number =>
+ new Date().getTime() - startTime.getTime();
+
+}

fix(logger): displat proper response time