Skip to content

Instantly share code, notes, and snippets.

@markmichon
Created March 9, 2020 02:04
Show Gist options
  • Save markmichon/a4abeae93009232bc5a6cbe463fdbbd7 to your computer and use it in GitHub Desktop.
Save markmichon/a4abeae93009232bc5a6cbe463fdbbd7 to your computer and use it in GitHub Desktop.

Revisions

  1. markmichon created this gist Mar 9, 2020.
    59 changes: 59 additions & 0 deletions devto.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    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));