UNPKG

@nofrills/http

Version:

Provides a simple, Fetch-based HTTP client.

69 lines 2.82 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const node_fetch_1 = require("node-fetch"); const Logger_1 = require("./Logger"); class HTTP { constructor() { this.log = Logger_1.Logger.extend(this.name); } delete(url) { return __awaiter(this, void 0, void 0, function* () { return this.send(url, yield this.request(), 'DELETE'); }); } get(url) { return __awaiter(this, void 0, void 0, function* () { return this.send(url, yield this.request(), 'GET'); }); } head(url) { return __awaiter(this, void 0, void 0, function* () { return this.send(url, yield this.request(), 'HEAD'); }); } patch(url, body) { return __awaiter(this, void 0, void 0, function* () { return this.send(url, yield this.request(body), 'PATCH'); }); } post(url, body) { return __awaiter(this, void 0, void 0, function* () { return this.send(url, yield this.request(body), 'POST'); }); } put(url, body) { return __awaiter(this, void 0, void 0, function* () { return this.send(url, yield this.request(body), 'PUT'); }); } send(url, init, method = 'GET') { return __awaiter(this, void 0, void 0, function* () { if (init.method === undefined) { init.method = method; } this.log.trace(`http.send:${method}:${url}`, JSON.stringify(init)); const request = new node_fetch_1.Request(url, init); const response = yield node_fetch_1.default(request); if (response.ok) { this.log.trace(`http:${response.status}:[${response.statusText}]: ${url}`); try { return yield response.json(); } catch (error) { this.log.error(`http.error:${response.status}`, response.statusText, error); } } throw new Error(`[${response.status}]: ${response.statusText} - ${method} request failed at ${url}`); }); } } exports.HTTP = HTTP; //# sourceMappingURL=Http.js.map