Skip to content

Instantly share code, notes, and snippets.

@andrewglind
Last active November 15, 2018 02:20
Show Gist options
  • Save andrewglind/b8a896c59939d46d1ff56081f19b6235 to your computer and use it in GitHub Desktop.
Save andrewglind/b8a896c59939d46d1ff56081f19b6235 to your computer and use it in GitHub Desktop.
Lightweight promise based REST API requests
class Request {
constructor(protocol, host, requestHandler, responseHandler) {
this.protocol = protocol
this.host = host
this.requestHandler = requestHandler
this.responseHandler = responseHandler
}
_request(path, method, requestData, headers) {
return new Promise((resolve, reject) => {
let req = this.protocol.request(
{
method,
host: this.host,
path,
headers
},
res => {
let { statusCode } = res
if (statusCode >= 400) reject({ response: {}, statusCode })
let responseData = ""
res.on("data", chunk => {
responseData += chunk
})
res.on("end", () => {
resolve({ response: responseData.length > 0 ? this.responseHandler(responseData) : {}, statusCode })
})
}
)
if (requestData) req.write(this.requestHandler(requestData))
req.on("error", err => {
reject(err)
})
req.end()
})
}
get(path, headers = {}) {
return this._request(path, "GET", null, headers)
}
post(path, data = {}, headers = {}) {
return this._request(path, "POST", data, headers)
}
put(path, data = {}, headers = {}) {
return this._request(path, "PUT", data, headers)
}
delete(path, headers = {}) {
return this._request(path, "DELETE", null, headers)
}
}
module.exports = (host = "localhost", protocol = require("http"), requestHandler = (data) => JSON.stringify(data), responseHandler = (data) => JSON.parse(data)) => new Request(protocol, host, requestHandler, responseHandler)
const jsonplaceholder = require("./request")("jsonplaceholder.typicode.com", require("https"))
// Async-Await
!(async () => {
try {
let { response } = await jsonplaceholder.get("/todos/1")
console.log(response)
} catch(e) {
console.log("Error", e)
}
})()
!(async () => {
try {
let { response } = await jsonplaceholder.post("/posts", { title: "", body: "bar", userId: 1 }, { "Content-type": "application/json" })
console.log(response)
} catch(e) {
console.log("Error", e)
}
})()
// Promise chaining
jsonplaceholder.get("/todos/1")
.then(({ response }) => console.log(response))
.catch(e => console.log("Error", e))
jsonplaceholder.post("/posts", { title: "", body: "bar", userId: 1 }, { "Content-type": "application/json" })
.then(({ response }) => console.log(response))
.catch(e => console.log("Error", e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment