Skip to content

Instantly share code, notes, and snippets.

@espeon
Created September 11, 2020 05:10
Show Gist options
  • Select an option

  • Save espeon/c33ad1e1736e1e6273aa55171e6f7cbd to your computer and use it in GitHub Desktop.

Select an option

Save espeon/c33ad1e1736e1e6273aa55171e6f7cbd to your computer and use it in GitHub Desktop.
const express = require("express");
const fs = require("fs");
const app = express();
function isValidURL(string) {
var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
return (res !== null && string.includes(".gif"))
};
app.get("/api/pika/", (req, res) => {
let pika = JSON.parse(fs.readFileSync(__dirname + "/public/pika.json"));
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
if (req.query.url) {
if (!isValidURL(req.query.url)) return res.send("This is not a valid image url.")
if (yourArray.indexOf("someString") > -1) return res.send("This url is already in the database.")
pika.push(req.query.url)
fs.writeFileSync(
__dirname + "/public/pika.json",
JSON.stringify(pika)
);
console.log(req.query.url, "has been submitted")
res.send("Thank you for your submission of " + req.query.url + ". It will be reviewed shortly.")
return;
}
let num = Math.round(Math.random() * pika.length);
res.json({ image: pika[num] });
});
app.get("/api/pika.gif", (req, res) =>{
let num = Math.round(Math.random() * pika.length);
req.pipe(request(pika[num]).on("response", remoteRes => {
// You can add/remove/modify headers here
remoteRes.headers["cache-control"] = 'public, max-age=7884000';
})).pipe(res);
})
let listener = app.listen(process.env.PORT, () => {
console.log(
"❗ Your app has restarted and is listening on port " +
listener.address().port
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment