-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
59 lines (53 loc) · 1.76 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
var express = require("express");
var http = require("http");
var GoogleImages = require("google-images");
var app = express();
var client = new GoogleImages("010943239557185514526:0hr49zbv1n4", "AIzaSyBO80Sy-frIgp3hbqddbm2NZoRGzKkXRp4");
var db = require("./db");
var bodyParser = require("body-parser");
var path = require("path");
app.use(express.static(path.join(__dirname, "public")));
app.use(bodyParser.urlencoded({
extended:false}));
app.use(bodyParser.json());
app.get("/api/latest/imagesearch/", function(req, res) {
db.getConnection(function(err, connection) {
var columns = ['term', 'time'];
connection.query("SELECT ?? FROM ?? ORDER BY ?? DESC LIMIT 10", [columns,'history', 'id'],function (err, results){
if (results.length > 0){
res.json(results);
}
connection.release();
if(!results.length){
res.end("Sorry, no results!");
}
if (err) throw err;
});
});
});
app.get("/api/imagesearch/:id", function(req, res) {
var id = req.params.id;
var arr = [];
var time = new Date();
var off = req.query.offset;
var data = {term: id, time: time};
client.search(id, {page:off}).then(function (images) {
db.getConnection(function(err, connection) {
connection.query("INSERT INTO history SET ?", data, function (err, results) {
connection.release();
if (err) throw err;
});
});
for (var i=0;i<images.length;i++){
arr.push({
url: images[i].url,
snippet: images[i].description,
thumbnail: images[i].thumbnail.url,
context: images[i].parentPage
});
}
res.json(arr);
});
});
app.listen(process.env.PORT || 5000);
console.log("Server running");