Skip to content

Instantly share code, notes, and snippets.

@Matthew-Burfield
Forked from cecilemuller/imgur.js
Created April 25, 2017 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Matthew-Burfield/5aefaaa82032ad3b9385bdae5358d755 to your computer and use it in GitHub Desktop.
Save Matthew-Burfield/5aefaaa82032ad3b9385bdae5358d755 to your computer and use it in GitHub Desktop.
Search images using the Imgur API
'use strict';
/* global XMLHttpRequest */
/* global process.env.API_IMGUR */
const querystring = require('querystring');
/**
* Fetches a page of results from the Imgur API.
*
* @param {String} options.q Query
* @param {Number} options.page Index of the page of results
* @param {Function} done Callback that receives the parsed response
*/
module.exports = ({q = '', page = 0} = {}, done) => {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState == XMLHttpRequest.DONE){
let response;
try {
response = JSON.parse(xhr.responseText);
} catch(e){
response = {};
}
if (response.success){
const parsed = response.data
.filter(result => !result.is_album)
.map(data => {
return {
title: data.title,
url: data.link,
width: data.width,
height: data.height
};
});
done(parsed);
} else {
done(false);
}
}
};
const url = 'https://api.imgur.com/3/gallery/search/top/' + page + '/?' + querystring.stringify({q});
xhr.open('GET', url, true);
xhr.setRequestHeader('Authorization', `Client-ID ${process.env.API_IMGUR}`);
xhr.send(null);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment