You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
1.1 KiB
JavaScript

import http from "http";
import https from "https";
import fs from "fs";
export class MemeHandler{
constructor(memeAPI, subreddits, allowedMedia){
this.memeAPI = memeAPI;
this.subreddits = subreddits;
this.allowedMedia = allowedMedia;
}
getRandomMeme(callback){
this.request(this.memeAPI+this.randomFromArray(this.subreddits), (res) => {
let sub = this.randomFromArray(res.subs);
callback(sub);
});
}
downloadMedia(url, filepath, callback){
const request = https.get(url, (res) => {
res.pipe(fs.createWriteStream(filepath));
res.on('end', () => {
callback();
})
});
}
request(url, callback){
http.get(url, res => {
let data = "";
res.on('data', chunk => {
data += chunk;
})
res.on('end', () => {
callback(JSON.parse(data))
})
})
}
randomFromArray(array){
return array[Math.floor(Math.random()*array.length)];
}
}