Last active
June 27, 2021 08:16
-
-
Save dhenson02/ed003d887af2b1bfbc9048abdc4049ef to your computer and use it in GitHub Desktop.
Promisify HTTPS connections with vanilla Node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const https = require('https'); | |
const defaultOptions = { | |
"port": 443, | |
"host": `127.0.0.1`, | |
"method": `GET`, | |
"headers": { | |
"Content-Type": `application/json`, | |
"Accept": `application/json`, | |
} | |
}; | |
/** | |
* @param {{ method: string, path: string, body: string|Object, ...?defaultOptions }} options | |
* @returns {Promise<{}>} | |
*/ | |
function request ( options = { | |
baseUrl: `https://${defaultOptions.host}:${defaultOptions.port}` | |
} ) { | |
const promise = new Promise(( resolve, reject ) => { | |
let { | |
path, | |
body, | |
baseUrl, | |
} = options; | |
if ( !path ) { | |
throw new Error(`Missing path for connection`); | |
} | |
const requestBody = typeof body === `object` | |
? JSON.stringify(body) | |
: (body || undefined); | |
const uri = `${baseUrl}/${path}`; | |
const reqOpts = { | |
...defaultOptions, | |
...options, | |
uri, | |
"body": requestBody, | |
}; | |
const bufferArray = []; | |
const req = https.request(reqOpts, res => { | |
res.on('error', ( e ) => { | |
reject(`Request failed: ${e.message}`); | |
}) | |
res.on('end', () => { | |
const data = Buffer.concat(bufferArray); | |
const obj = JSON.parse(data); | |
if ( obj.error ) { | |
return reject(`[${obj.status}] - ${JSON.stringify(obj.error, null, 2)}`); | |
} | |
return resolve(obj); | |
}) | |
res.on('data', data => { | |
bufferArray[ bufferArray.length ] = data; | |
}); | |
}); | |
req.end(); | |
}); | |
return promise.catch(e => { console.trace(e); return {}; }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment