Created
August 6, 2020 04:32
-
-
Save axetroy/6571edfe89330cf56a42df8c7bd6f6ca to your computer and use it in GitHub Desktop.
HTTP printer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type HTTPHeaders = { [key: string]: string | string[] }; | |
interface HTTPResponse { | |
status: number; | |
headers: HTTPHeaders; | |
body: unknown; | |
} | |
class Printer { | |
#url!: string; | |
#method!: string; | |
#headers!: HTTPHeaders; | |
#data!: unknown; | |
#date!: Date; | |
public start( | |
url: string, | |
method: string, | |
headers: HTTPHeaders, | |
data: unknown | |
) { | |
this.#url = url; | |
this.#method = method; | |
this.#date = new Date(); | |
this.#headers = headers; | |
this.#data = data; | |
} | |
public end(response: HTTPResponse) { | |
console.groupCollapsed( | |
`[${this.#method.toUpperCase()}]: ${this.#url} ${response.status}` | |
); | |
{ | |
this.printHeaders(this.#headers, "Request"); | |
console.log(); | |
this.printBody(this.#data, "Request"); | |
console.log(); | |
this.printHeaders(response.headers, "Response"); | |
console.log(); | |
this.printBody(response.body, "Response"); | |
} | |
console.groupEnd(); | |
} | |
private printHeaders(headers: HTTPHeaders, title: string) { | |
console.groupCollapsed(`${title} Headers:`); | |
for (const key in headers) { | |
const value = headers[key]; | |
console.log(`${key}: ${value}`); | |
} | |
console.groupEnd(); | |
} | |
private printBody(body: unknown, title: string) { | |
console.groupCollapsed(`${title} Body:`); | |
const type = Object.prototype.toString | |
.call(body) | |
.split(" ")[1] | |
.replace(/\]$/, ""); | |
switch (type) { | |
case "Date": | |
console.log(body); | |
case "String": | |
console.log(`"${body}"`); | |
break; | |
case "Number": | |
console.log(body); | |
break; | |
case "Object": | |
console.log(body); | |
break; | |
default: | |
console.log(body); | |
break; | |
} | |
console.groupEnd(); | |
} | |
} | |
const logger = new Printer(); | |
logger.start( | |
"/api/user", | |
"GET", | |
{ | |
foo: "bar", | |
"Content-Type": "application/json", | |
}, | |
{ | |
id: "xxxxx", | |
} | |
); | |
logger.end({ | |
status: 500, | |
headers: { | |
"accept-ranges": "bytes", | |
"access-control-allow-origin": "*", | |
age: "265510", | |
"cache-control": "public, max-age=31536000", | |
"content-encoding": "gzip", | |
"content-length": "87186", | |
"content-type": "text/javascript", | |
date: "Wed, 22 Jul 2020 11:00:21 GMT", | |
expires: "Thu, 22 Jul 2021 11:00:21 GMT", | |
"last-modified": "Wed, 06 May 2020 18:47:58 GMT", | |
server: "sffe", | |
status: "200", | |
vary: "Accept-Encoding", | |
}, | |
body: null, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment