-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
57 lines (52 loc) · 2.32 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
var express = require("express")
var app = express()
var Bing = require('node-bing-api')({accKey: process.env.ACC_KEY})//ACC_KEY set via command line
var mongoose = require("mongoose")
var searchString = require("./models/searchString")
var filtered = require("./filtered")
var history = require("./history")
var resultQuant = 10
var port = (process.env.PORT || 3000)
var address = process.env.IP
// mongoose.connect('mongodb://' + address + '/image_search')//used for local connection
mongoose.connect(process.env.MONGOLAB_URI)//MONGOLAB_URI set via command line
app.get('/', function(req, res) {
res.set({'content-type': 'application/json; charset=utf-8'})
res.end("To search for images, type '/search/' at the end of the root address in the address bar followed by a search string. This string may optionally be followed by '?offset={number}' to display the specified result page number. \n\nTo get the 10 most recent searches, type '/history' at the end of the root address in the address bar.")
})
app.get('/search/:searchTerm(*)', function(req, res) {
var searchTerm = req.params.searchTerm
var offset
req.query.offset ? offset = (req.query.offset - 1) * resultQuant : offset = 0
if (offset < 0) offset = 0
var newSearchString = searchString({'search string': searchTerm, 'date': new Date()})
newSearchString.save(function(err) {
if (err) throw err
})
Bing.images(searchTerm, {
top: resultQuant, // Number of results (max 50)
skip: offset // Number of results to skip
}, function(error, resp, body){
var arr = []
for (var i = 0; i < body.value.length; i++) {
arr.push(new filtered(body.value[i]))
}
res.set({'content-type': 'application/json; charset=utf-8'})
res.end(JSON.stringify(arr))
// res.json(arr)//alternative to the above two lines
})
})
app.get('/history', function(req, res) {
searchString.find({}, function(err, data) {
if (err) throw err
var arr = []
var start
data.length - resultQuant < 0 ? start = 0 : start = data.length - resultQuant
for (var i = start; i < data.length; i++) {
arr.push(new history(data[i]))
}
res.set({'content-type': 'application/json; charset=utf-8'})
res.end(JSON.stringify(arr))
})
})
app.listen(port)