Created
March 9, 2020 02:04
-
-
Save markmichon/a4abeae93009232bc5a6cbe463fdbbd7 to your computer and use it in GitHub Desktop.
Dev.to API client example
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 fetch = require("isomorphic-unfetch"); | |
const querystring = require("querystring"); | |
class DevTo { | |
constructor(config) { | |
this.api_key = config.api_key; | |
this.basePath = "https://dev.to/api"; | |
} | |
request(endpoint = "", options = {}) { | |
let url = this.basePath + endpoint; | |
let headers = { | |
api_key: this.api_key, | |
"Content-type": "application/json" | |
}; | |
let config = { | |
...options, | |
...headers | |
}; | |
return fetch(url, config).then(r => { | |
if (r.ok) { | |
return r.json(); | |
} | |
throw new Error(r); | |
}); | |
} | |
getArticles(options) { | |
let qs = options ? "?" + querystring.stringify(options) : ""; | |
let url = "/articles" + qs; | |
let config = { | |
method: "GET" | |
}; | |
return this.request(url, config); | |
} | |
getArticleById(id) { | |
let url = "/articles/" + id; | |
return this.request(url, {}); | |
} | |
createArticle(body) { | |
const options = { | |
method: "POST", | |
body: JSON.stringify(body) | |
}; | |
return this.request("/articles", options); | |
// Optional: add your own .catch to process/deliver errors or fallbacks specific to this resource | |
} | |
} | |
let api = new DevTo({ | |
api_key: process.env.SECRET | |
}); | |
api | |
.getArticles({ username: "bearer", page: 1 }) | |
.then(data => console.log(data)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment