-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
93 lines (74 loc) · 2.57 KB
/
server.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
var express = require('express');
var app = express();
var path = require('path');
var mongo = require("mongodb").MongoClient;
var dburl =process.env.dburl;
var GoogleSearch = require('google-search');
var googleSearch = new GoogleSearch({
key: process.env.apiKey,
cx: process.env.cx
});
app.get('/api/imagesearch/:query(*)',function(req,res){
var query = req.params.query;
var qoffset =req.query.offset ? req.query.offset : 1;
var date =new Date().toISOString();
console.log(query);
if (query != "favicon.ico"){
googleSearch.build({
q: query,
start: 2,
num: qoffset, // Number of search results to return between 1 and 10, inclusive
searchType: 'image',
siteSearch: "www.google.com" // Restricts results to URLs from a specified site
}, function(error, response) {
res.send(response.items.map(function(items){
return {
url: items.link,
snippet: items.snippet,
thumbnail: items.image.thumbnailLink,
context: items.image.contextLink
}
}))
});
mongo.connect(dburl, function (err, db) {
if (err) {
res.end('Unable to connect to the mongoDB server. Error:');
return console.log(err);
} else {
console.log('Connection established to', dburl);
var imgsearchList = db.collection('imgabstraction');
imgsearchList.insert([{term: query, when: date}],function(error, results){
});
db.close();
}
});
}else{
res.send("Format queries correctly");
}
});
app.get('/api/latest', function(req,res){
mongo.connect(dburl, function (err, db) {
if (err) throw err;
db.collection("imgabstraction").find({}).sort({_id: -1}).limit(10).toArray(function(err, result) {
if (err) throw err;
res.send(result);
db.close();
});
});
});
app.get('/', function(req,res){
var fileName = path.join(__dirname, '/views/index.html');
res.sendFile(fileName, function (err) {
if (err) {
console.log(err);
res.status(err.status).end();
}
else {
console.log('Sent:', fileName);
}
});
});
// listen for requests :)
var listener = app.listen(process.env.PORT, function () {
console.log('Your app is listening on port ' + listener.address().port);
});