-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
138 lines (100 loc) · 2.51 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
var express = require("express");
var app = express();
const Sequelize = require('sequelize');
const sequelize = new Sequelize('c9', 'unknownazazel', '', {
host: process.env.IP,
dialect: 'mysql'
});
var cx = '003697610006780978114:my8kdtrflag';
var appid = 'gseapifreecodecamp';
const GoogleImages = require('google-images');
const client = new GoogleImages(cx, appid);
var Bing = require('node-bing-api')({
accKey: "12b3a7076dcb4f2eadd0bbd6aa96682c"
});
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
});
const model = sequelize.define('imgsearch', {
query: {
type: Sequelize.STRING,
allowNull: false,
unique: true
},
}, {
createdAt: false
}
);
/*//test val
model.sync({
force: true
}).then(() => {
return model.create({
query: 'test'
});
});
*/
app.get("/recent", function(req, res) {
model.findAll({
limit: 10,
order: [
['updatedAt', 'DESC']
]
}).then(result => {
res.send(result);
})
});
app.get('/favicon.ico', function(req, res) {
res.sendStatus(204);
});
app.get('/*', function(req, resp) {
//remove trailing slash
var url = urldecode(JSON.stringify(req.originalUrl)).replace(/\//, "").replace(/\"/g, "");
if (url == '') {
url = 'x';
}
var ret = [];
var off = 0;
if (req.query.offset) {
off = req.query.offset;
}
model.findOrCreate({
where: {
query: url
}
}).spread((item, created) => {
if (!created) {
model.update({
query: url
}, {
where: {
query: item.query
}
}).then((x, y) => {
console.log(y);
})
}
});
Bing.images(url, function(error, res, body) {
//resp.send(JSON.stringify(body, null, 4));
for (var i = 0; i < body.value.length; i++) {
var tmp = {
alt: body.value[i].name,
image: body.value[i].contentUrl,
source: body.value[i].hostPageUrl
};
ret.push(tmp);
}
resp.send(ret);
}, {
skip: off
});
});
app.listen(process.env.PORT, function() {
console.log('Example app listening on port' + process.env.PORT);
});
function urldecode(str) {
return decodeURIComponent((str + '').replace(/\+/g, '%20'));
}