UNPKG

@tsed/cli-core

Version:
77 lines (76 loc) 2.82 kB
import { __decorate, __metadata, __param } from "tslib"; import querystring from "node:querystring"; import { getValue } from "@tsed/core"; import { inject, Opts } from "@tsed/di"; import { Logger } from "@tsed/logger"; import { logToCurl } from "../utils/logToCurl.js"; let CliHttpLogClient = class CliHttpLogClient { // @ts-ignore constructor(options = {}) { this.logger = inject(Logger); this.callee = options.callee || "http"; } onSuccess(options) { return this.logger.debug({ ...this.formatLog(options), status: "OK" }); } onError(error, options) { const origin = this.errorMapper(error); this.logger.warn({ ...this.formatLog(options), status: "KO", callee_code: origin.code, callee_error: origin.message, callee_request_qs: options.params && querystring.stringify(options.params), callee_request_headers: options.headers, callee_request_body: options.data && JSON.stringify(options.data), callee_response_headers: origin.headers, callee_response_body: origin.body && JSON.stringify(origin.body), callee_response_request_id: origin.x_request_id, curl: this.logToCurl(options) }); } logToCurl(options) { return logToCurl(options); } getStatusCodeFromError(error) { return getValue(error, "response.status", getValue(error, "response.statusCode", getValue(error, "status"))); } getHeadersFromError(error) { return getValue(error, "response.headers", getValue(error, "headers")); } getResponseBodyFromError(error) { return getValue(error, "response.data", getValue(error, "data")); } formatLog(options) { const { startTime, url, method } = options; const { callee } = this; const duration = new Date().getTime() - startTime; return { callee, url, method, callee_qs: options.params && querystring.stringify(options.params), duration: isNaN(duration) ? undefined : duration }; } errorMapper(error) { const statusCode = this.getStatusCodeFromError(error); const headers = this.getHeadersFromError(error); const body = this.getResponseBodyFromError(error); return { message: error.message || statusCode, code: statusCode, headers, body, x_request_id: getValue(error, "response.headers.x-request-id", getValue(error, "headers.x-request-id")) }; } }; CliHttpLogClient = __decorate([ __param(0, Opts), __metadata("design:paramtypes", [Object]) ], CliHttpLogClient); export { CliHttpLogClient };