/ts-http-types

TypeScript library for JSON serialisation of HTTP exchanges.

Primary LanguageTypeScriptMIT LicenseMIT

HTTP Types in TypeScript

Build Status MIT licensed npm version

Typescript library to read and write records of HTTP exchanges in the http-types format.

Install

$ npm install http-types

Writing HTTP exchanges

Using HttpExchangeWriter a recording of HTTP traffic can be serialised for use with any program that can handle the http-types format.

const writer = new HttpExchangeWriter();

const request = HttpRequestBuilder.fromPath({
  timestamp: timestamp,
  method: HttpMethod.GET,
  protocol: HttpProtocol.HTTPS,
  host: "example.com",
  headers: {
    "accept-encoding": "gzip, deflate, br",
    "cache-control": ["no-cache", "no-store"]
  },
  path: "/my/path?a=b&q=1&q=2",
  body: "request string body"
});

const response = HttpResponseBuilder.from({
  headers: {
    "accept-encoding": "gzip, deflate, br",
    "cache-control": "no-cache"
  },
  statusCode: 404,
  body: "response string body"
});

writer.write({ request, response });

// [...] (write multiple exchanges)

// writer.buffer contains the exchanges in the http-types JSON Lines format.
console.log(writer.buffer);

A HTTP request can also be created from query parameters as an object. The below request is identical to the one created above:

const request = HttpRequestBuilder.fromPathnameAndQuery({
  timestamp: timestamp,
  method: HttpMethod.GET,
  protocol: HttpProtocol.HTTPS,
  host: "example.com",
  headers: {
    "accept-encoding": "gzip, deflate, br",
    "cache-control": ["no-cache", "no-store"]
  },
  pathname: "/my/path",
  query: {
    a: "b",
    q: ["1", "2"]
  },
  body: "request string body"
});

Reading HTTP exchanges

With HttpExchangeReader http-types recordings can be read for processing:

HttpExchangeReader.fromJsonLines(writer.buffer, exchange => {
  expect(exchange.request.host).toBe("example.com");
  expect(exchange.request.query.get("a")).toEqual("b");
});