Add random and image routes
This commit is contained in:
parent
c9ddb2563e
commit
14bacb3e13
1 changed files with 23 additions and 5 deletions
28
index.js
28
index.js
|
@ -4,9 +4,8 @@ app.use(require("cors")());
|
|||
const fetch = require("node-fetch");
|
||||
const jsdom = require("jsdom");
|
||||
|
||||
app.get("/", (request, response) => {
|
||||
response.writeHead(200, { "Content-Type": "application/json" });
|
||||
fetch("https://www.bing.com/images/search?q=" + request.url.substring(request.url.indexOf("?") + 1))
|
||||
async function getResults(query) {
|
||||
return await fetch("https://www.bing.com/images/search?q=" + query)
|
||||
.then(response => response.text())
|
||||
.then(text => new jsdom.JSDOM(text).window.document)
|
||||
.then(document => {
|
||||
|
@ -19,9 +18,28 @@ app.get("/", (request, response) => {
|
|||
}
|
||||
results.push(src);
|
||||
}
|
||||
response.write(JSON.stringify(results));
|
||||
response.end();
|
||||
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.end();
|
||||
});
|
||||
});
|
||||
|
||||
app.listen(process.argv[2] ? process.argv[2] : 3000);
|
||||
|
|
Reference in a new issue