Add random and image routes

main
Elnu 2 years ago
parent c9ddb2563e
commit 14bacb3e13

@ -4,9 +4,8 @@ app.use(require("cors")());
const fetch = require("node-fetch"); const fetch = require("node-fetch");
const jsdom = require("jsdom"); const jsdom = require("jsdom");
app.get("/", (request, response) => { async function getResults(query) {
response.writeHead(200, { "Content-Type": "application/json" }); return await fetch("https://www.bing.com/images/search?q=" + query)
fetch("https://www.bing.com/images/search?q=" + request.url.substring(request.url.indexOf("?") + 1))
.then(response => response.text()) .then(response => response.text())
.then(text => new jsdom.JSDOM(text).window.document) .then(text => new jsdom.JSDOM(text).window.document)
.then(document => { .then(document => {
@ -19,6 +18,25 @@ app.get("/", (request, response) => {
} }
results.push(src); results.push(src);
} }
return results;
});
}
app.get("/random/:query*.jpg", (request, response) => {
getResults(request.params.query).then(results => {
response.redirect(results[Math.floor(Math.random() * results.length)]);
});
});
app.get("/:query*.jpg", (request, response) => {
getResults(request.params.query).then(results => {
response.redirect(results[0]);
});
});
app.get("/:query", (request, response) => {
response.writeHead(200, { "Content-Type": "application/json" });
getResults(request.params.query).then(results => {
response.write(JSON.stringify(results)); response.write(JSON.stringify(results));
response.end(); response.end();
}); });