-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (66 loc) · 2.09 KB
/
index.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
var express = require('express');
var path = require('path');
var Cacheman = require('cacheman')
var FileCache = require('cacheman-file')
var sortedObject = require('sorted-object')
var hash = require('object-hash');
var google = require('googleapis')
var search = google.customsearch({
version: 'v1',
params: { auth: process.env.CSE_AUTH, cx: process.env.CSE_CX }
});
if (process.env.CSE_CX_RU) {
var searchRu = google.customsearch({
version: 'v1',
params: { auth: process.env.CSE_AUTH, cx: process.env.CSE_CX_RU }
})
}
if (!process.env.CSE_AUTH || !process.env.CSE_CX) {
console.error('Specify CSE_AUTH, CSE_CX environmental variables to run google search');
process.exit();
}
var app = express()
var cache = new Cacheman('search', {
ttl: 86400,
engine: new FileCache({
tmpDir: path.join(process.cwd(), 'cache')
})
})
const CACHE_STATUS_HEADER = 'X-Cache-Status';
var cacheKey = function(req) {
return hash(sortedObject(req.query))
}
var cacheMiddleware = function(req, res, next) {
if (!req.query.q) {
res.status(400).end();
return console.log('No query specified');
}
cache.get(cacheKey(req), (err, value) => {
if (err || value === null) {
next()
} else {
res.set(CACHE_STATUS_HEADER, 'Hit').send(value)
}
})
}
var proxyMiddleware = function(req, res, next) {
res.set(CACHE_STATUS_HEADER, 'Miss');
var key = cacheKey(req);
var query = req.query;
if (!query.siteSearch) {
query.q += (query.lang === 'ru' ? ' site:kb.x-cart.ru OR site:devs.x-cart.ru' : ' site:kb.x-cart.com OR site:devs.x-cart.com');
}
var api = search;
if (query.lang === 'ru' && typeof(searchRu) !== 'undefined') {
api = searchRu;
}
api.cse.list(query, (err, search) => {
cache.set(key, search);
res.send(search);
})
}
var handler = [cacheMiddleware, proxyMiddleware];
app.use('/search', handler)
app.listen(process.env.PORT || 3000, function () {
console.log('Google Search caching proxy has started successfully')
})