Skip to content

Instantly share code, notes, and snippets.

@d0whc3r
Last active December 16, 2020 15:28
Show Gist options
  • Select an option

  • Save d0whc3r/840666d65b79eb3910fee840ce39f11b to your computer and use it in GitHub Desktop.

Select an option

Save d0whc3r/840666d65b79eb3910fee840ce39f11b to your computer and use it in GitHub Desktop.

Revisions

  1. d0whc3r revised this gist Dec 16, 2020. 1 changed file with 4 additions and 4 deletions.
    8 changes: 4 additions & 4 deletions https-wrapper.js
    Original file line number Diff line number Diff line change
    @@ -2,10 +2,10 @@ const https = require('https');

    /**
    * Make a https request
    * @param url {string}
    * @param options {import('https').RequestOptions}
    * @param postData {Record<string, any>}
    * @returns {Promise<unknown>}
    * @param {string} url
    * @param {import('https').RequestOptions} options
    * @param {Record<string, any>} [postData]
    * @returns {Promise<{ data: Record<string, any>, statusCode: number, statusMessage: string }>}
    */
    function request(url, options, postData) {
    return new Promise((resolve, reject) => {
  2. d0whc3r created this gist Dec 16, 2020.
    36 changes: 36 additions & 0 deletions https-wrapper.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    const https = require('https');

    /**
    * Make a https request
    * @param url {string}
    * @param options {import('https').RequestOptions}
    * @param postData {Record<string, any>}
    * @returns {Promise<unknown>}
    */
    function request(url, options, postData) {
    return new Promise((resolve, reject) => {
    const req = https.request(url, options, (res) => {
    let body = '';
    res.setEncoding('utf8');
    res.on('data', (chunk) => {
    body += chunk;
    });
    res.on('end', () => {
    const data = JSON.parse(body);
    const result = { data, statusCode: res.statusCode, statusMessage: res.statusMessage };
    if (res.statusCode < 200 || res.statusCode >= 300) {
    reject(result);
    } else {
    resolve(result);
    }
    });
    });
    req.on('error', (e) => {
    reject(e);
    });
    if (postData) {
    req.write(postData);
    }
    req.end();
    });
    }