Skip to content

Commit

Permalink
httpRequest now returns a promise and no longer takes a callback
Browse files Browse the repository at this point in the history
  • Loading branch information
rattletone committed Jul 1, 2019
1 parent 3f6eabb commit 36aec4c
Showing 1 changed file with 44 additions and 36 deletions.
80 changes: 44 additions & 36 deletions lib/ApiRequest.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,34 @@ const { URL, URLSearchParams } = require("url");
const crypto = require("crypto");
const http = require("http");

function httpRequest(options, reqBody, callback) {
const request = http.request(options, response => {
let resBody = "";

response.on("data", data => {
resBody += data;
});

response.on("end", () => {
callback(null, JSON.parse(resBody));
function httpRequest(options, reqBody) {
return new Promise((resolve, reject) => {
const request = http.request(options, response => {
let resBody = "";

response.on("data", data => {
resBody += data;
});

response.on("end", () => {
resolve(resBody);
});

response.on("error", err => {
reject(err);
});
});

response.on("error", err => {
callback(err, null);
request.on("error", err => {
reject(err);
});

if(options.method === "POST") {
request.write(reqBody);
}

request.end();
});

request.on("error", err => {
callback(err, null);
});

if(options.method === "POST") {
request.write(reqBody);
}

request.end();
}

class ApiRequest {
Expand Down Expand Up @@ -112,21 +114,27 @@ class ApiRequest {
options.path += `?${querystring}`;
}

if(callback) {
httpRequest(options, querystring, callback);
const request = httpRequest(options, querystring)
.then(response => {
return new Promise((resolve, reject) => {
const data = JSON.parse(response);

return;
resolve(data);
});
});

if(callback) {
request
.then(data => {
callback(null, data);
})
.catch(err => {
callback(err, null);
});
}
else {
return request;
}

return new Promise((resolve, reject) => httpRequest(options, querystring, (err, data) => {
if(err) {
reject(err);

return;
}

resolve(data);
}));
}
}

Expand Down

0 comments on commit 36aec4c

Please sign in to comment.