@atomist/automation-client
Version:
Atomist API for software low-level client
81 lines • 3.33 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const _ = require("lodash");
const os = require("os");
const child_process_1 = require("../../util/child_process");
const logger_1 = require("../../util/logger");
const retry_1 = require("../../util/retry");
const httpClient_1 = require("./httpClient");
/**
* Curl based HttpClient implementation.
*/
class CurlHttpClient {
exchange(url, options = {}) {
const optionsToUse = Object.assign(Object.assign({}, httpClient_1.DefaultHttpClientOptions), options);
// Prepare headers
const headers = _.map(optionsToUse.headers, (v, k) => `${k}: ${v}`);
// Prepare the provided raw curl options
const rawOptions = _.map(optionsToUse.options, (v, k) => {
if (k.length === 1) {
return [`-${k}`, v];
}
else {
return [`--${k}`, v];
}
});
const request = () => __awaiter(this, void 0, void 0, function* () {
try {
const result = yield child_process_1.execPromise("curl", [
"-X", optionsToUse.method,
url,
"-s",
"--write-out",
"HTTPSTATUS:%{http_code}",
..._.flatten(headers.map(h => (["-H", h]))),
..._.flatten(rawOptions),
...(options.body ? ["-d", JSON.stringify(options.body)] : []),
]);
const parts = result.stdout.split("HTTPSTATUS:");
let body;
try {
body = JSON.parse(parts[0]);
}
catch (e) {
logger_1.logger.warn(`Failed to parse response from curl: ${e.message}`);
}
return {
status: +parts[1],
body: (body) ? body : parts[0],
};
}
catch (e) {
logger_1.logger.error(`Failed to curl: ${e.message}`);
throw e;
}
});
return retry_1.doWithRetry(request, `Requesting '${url}'`, optionsToUse.retry);
}
}
exports.CurlHttpClient = CurlHttpClient;
/**
* HttpClientFactory that creates HttpClient instances backed by curl.
*/
class CurlHttpClientFactory {
create(url) {
if (os.platform() === "win32") {
throw new Error("CurlHttpClient is not available on Windows.");
}
return new CurlHttpClient();
}
}
exports.CurlHttpClientFactory = CurlHttpClientFactory;
//# sourceMappingURL=curlHttpClient.js.map