UNPKG

pluto-http-client

Version:

HTTP client for NodeJS. Inspired in the Java JAX-RS spec so you can expect excellence, versatility and extensibility.

112 lines (111 loc) 3.43 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.NodeResponse = void 0; const media_type_1 = require("../media-type"); const collections_1 = require("../../utils/collections"); const cookie_1 = require("../cookie"); const stream_1 = require("stream"); const buffer_1 = require("buffer"); const entity_tag_1 = require("../entity-tag"); const response_1 = require("../response"); class NodeResponse { constructor(_headers, response, _statusCode = -1) { this._headers = _headers; this.response = response; this._statusCode = _statusCode; this._reader = response; } getHeaders() { return this._headers; } getCookies() { if (!this._cookies) { this._cookies = new collections_1.MultiValueMap(); if (Array.isArray(this._headers['set-cookie'])) { this._headers['set-cookie'].forEach((c) => { const someCookie = cookie_1.Cookie.fromString(c); if (someCookie) { this._cookies.add(someCookie); } }); } } return this._cookies; } getDate() { if (this._headers["date"]) { return new Date(this._headers["date"]); } } getHeaderString(key) { return (this._headers[key.toLowerCase()] || "").toString(); } getLastModified() { if (this._headers["last-modified"]) { return new Date(this._headers["last-modified"]); } } getMediaType() { if (!this._mediaType) { try { this._mediaType = media_type_1.MediaType.fromString(this._headers["content-type"]); } catch (e) { if (process.env.PLUTO_DEBUG) { console.debug("Error parsing ETAG:", e); } } } return this._mediaType; } getEtag() { if (!this._etag) { try { this._etag = entity_tag_1.EntityTag.fromString(this._headers['etag']); } catch (e) { if (process.env.PLUTO_DEBUG) { console.debug("Error parsing ETAG:", e); } } } return this._etag; } getStatus() { return this._statusCode; } getStatusInfo() { return new response_1.StatusType(this.getStatus()); } readEntity(unmarshaller) { if (unmarshaller instanceof stream_1.Writable) { return this._reader.pipe(unmarshaller); } return new Promise((resolve, reject) => { const buff = []; this._reader.on('error', (e) => { reject(e); }); this._reader.on('data', (chunk) => { buff.push(chunk); }); this._reader.on('end', () => { unmarshaller .unmarshal(buffer_1.Buffer.concat(buff), this.getMediaType()) .then((t) => { resolve(t); }) .catch((e) => { reject(e); }); }); }); } pipe(transformer) { this._reader = this._reader.pipe(transformer); } close() { this._reader.destroy(); } } exports.NodeResponse = NodeResponse;