Asynchronous/Promise based News API Client

by Lloyd Atkinson

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.min.js"></script>
<div id="news-area">
    <ul>

    </ul>
</div>

JavaScript

var NewsApiClient = (function() {
    function NewsApiClient(apiKey) {
        if (!apiKey) {
            throw 'Invalid News API key.';
        }

        this.newsApiKey = apiKey;
    }

    NewsApiClient.prototype.get = async function(source, sortBy) {
        return await axios.get('https://newsapi.org/v1/articles', {
                params: {
                    source: source,
                    apiKey: this.newsApiKey,
                    sortBy: sortBy
                }
            })
            .then(function(response) {
                return response.data.articles;
            })
            .catch(function(error) {
                return error;
            });
    };

    NewsApiClient.prototype.getTop = async function(source) {
        return this.get(source, 'top');
    };

    NewsApiClient.prototype.getLatest = async function(source) {
        return this.get(source, 'latest');
    };

    NewsApiClient.prototype.getPopular = async function(source) {
        return this.get(source, 'popular');
    };

    return NewsApiClient;
}());


let newsClient = new NewsApiClient('6017b19103d04b0cbfcd48b14114c809');
let articles = newsClient.getLatest('ars-technica').then((articles) => {
    console.log(articles);
    for (let article of articles) {
        $('#news-area ul').append($('<li>').text(article.title));
    }
});