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.
43 lines
1.2 KiB
JavaScript
43 lines
1.2 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);
|
|
console.log("got sub => ");
|
|
console.log(sub)
|
|
callback(sub);
|
|
});
|
|
}
|
|
downloadMedia(url, filepath, callback){
|
|
const request = https.get(url, (res) => {
|
|
res.pipe(fs.createWriteStream(filepath));
|
|
res.on('end', () => {
|
|
console.log(`downloaded media => ${filepath}`);
|
|
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)];
|
|
}
|
|
} |