HTTP printer

index.ts
复制


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,
});


大牛们的评论:朕有话说

还没有人评论哦,赶紧抢沙发!