UNPKG

@fabrix/spool-repl

Version:
85 lines (84 loc) 2.89 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const lodash_1 = require("lodash"); const http_1 = require("http"); const config = require("./config"); exports.Http = { init(app) { this.app = app; }, get(url, headers) { this.request('get', url, null, null, headers); }, options(url, params, contentType, headers) { this.request('options', url, params, contentType, headers); }, head(url, headers) { this.request('head', url, null, null, headers); }, post(url, params, contentType, headers) { contentType = contentType || 'application/json'; this.request('post', url, params, contentType, headers); }, patch(url, params, contentType, headers) { contentType = contentType || 'application/json'; this.request('patch', url, params, contentType, headers); }, put(url, params, contentType, headers) { contentType = contentType || 'application/json'; this.request('put', url, params, contentType, headers); }, delete(url, params, contentType, headers) { contentType = contentType || 'application/json'; this.request('delete', url, params, contentType, headers); }, request(method, url, params, contentType, headers) { const log = this.app.log; headers = headers || { 'Accept': 'application/json' }; if (!url.startsWith('/')) { url = '/' + url; } const configExtends = Object.assign(config, this.app.config.repl || {}); const options = { host: 'localhost', port: this.app.config.web.port, method: method, path: url, headers: {} }; if (params !== null && typeof params !== 'string') { params = JSON.stringify(params); } if (contentType !== null) { options.headers = { 'Content-Type': contentType, 'Content-Length': Buffer.byteLength(params) }; } if (headers !== null) { options.headers = lodash_1.merge(headers, options.headers); } const req = http_1.request(options, (resp) => { let body = ''; resp.setEncoding(configExtends.httpEncoding); resp.on('data', (chunk) => { body += chunk; }); resp.on('end', () => { try { const response = JSON.parse(body); log.info(resp.statusCode, response); } catch (e) { log.info(resp.statusCode, body); } }); }).on('error', (e) => { log.error('Got error: ' + e.message); }); if (params) { req.write(params); } req.end(); } };