UNPKG

savory

Version:

A command-line interface for operating your Codefresh account

64 lines (57 loc) 2.64 kB
const fp = require('lodash/fp'), qs = require('qs'), url = require('url'), kefir = require('kefir'), https = require('https'); const API_BASE_PATH = "/api"; const httpClientFactory = (function(){ const PARSERS = [ { "test": (contentType)=> /^application\/json/i.test(contentType), "parser": JSON.parse }, { "test": (contentType)=> /^text\/plain/i.test(contentType), "parser": fp.toString }, { "test": (contentType)=> /^text\/html/i.test(contentType), "parser": fp.toString } ]; return (apiEndpointUrl, apiKey)=> { return (path, queryString = {}, method = "GET", payload = null)=> { let payloadString = JSON.stringify(payload), req = https.request({ ...url.parse(apiEndpointUrl), headers: Object.assign( { "Authorization": apiKey }, payload && { "Content-Type": "application/json", "Content-Length": payloadString.length } ), method, path: [[API_BASE_PATH, path].join('/'), qs.stringify(queryString)].filter(Boolean).join('?') }); req.end(payload && payloadString); return kefir .fromEvents(req, 'response') .merge(kefir.fromEvents(req, 'error').flatMap(kefir.constantError)) .flatMap((response)=> { return kefir .fromEvents(response, 'data') .takeUntilBy(kefir.fromEvents(response, 'end').take(1)) .scan(fp.concat, []) .last() .map( fp.pipe( Buffer.concat, (PARSERS.find(({ test })=> test(fp.get('headers.content-type', response))) || { parser: fp.identity }).parser ) ) .flatMap(kefir[response.statusCode === 200 ? "constant" : "constantError"]); }) .take(1) .takeErrors(1) .toPromise(); }; }; })(); module.exports = Object.assign( httpClientFactory, { middleware: ({ apiKey, apiEndpointUrl, ...argv })=> ({ ...argv, _httpClient: httpClientFactory(apiEndpointUrl, apiKey) }) } );