-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
306 lines (245 loc) · 10.3 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
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
'use strict'
require('dotenv').config();
const flash = require('express-flash');
const express = require('express');
const cors = require('cors');
const superagent = require('superagent');
const pg = require('pg');
const methodOverride = require('method-override');
const PORT = process.env.PORT || 8000;
const app = express();
const client = new pg.Client(process.env.DATABASE_URL);
client.on('error', errorHandler);
app.use(express.static('./public'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(methodOverride('_method'));
app.set('view engine', 'ejs');
app.use(cors());
app.use(flash());
var session = require('express-session');
app.use(session({
cookie: { maxAge: 60000 },
secret: 'woot',
resave: false,
saveUninitialized: false
}));
app.get('/search/new', (request, response) => {
response.render('pages/search');
});
// we need to figure out how to get the results of two apis in one response
// we can combine the array for each api in one array using push and then render the full array and we should remeber to have the same property names
/////////////////////////////////search page ////////////////////////////////////////////////////
app.post('/search', (request, response) => {
let fullArr = [];
let searchType = request.body.selectType;
let apiSelect = request.body.selectApi;
let searchKeyword = request.body.picName;
let unsplashKey = process.env.UNSPLASH_KEY;
let videoKey = process.env.VIDEO_KEY;
let videoURL = `https://pixabay.com/api/videos/?key=${videoKey}&q=${searchKeyword}`
let imageUrlPix = `https://pixabay.com/api/?key=16102900-d7963a65628f8edaa82e9259f&q=${searchKeyword}`;
let unsplashURL = `https://api.unsplash.com/search/photos?query=${searchKeyword}&client_id=${unsplashKey}`;
superagent.get(imageUrlPix)
.then((pixRes) => {
let pixData = pixRes.body.hits;
let pixDataArray = pixData.map((data) => {
return new Photos(data);
});
pixDataArray.forEach((item) => fullArr.push(item))
return (fullArr);
}).then((fullArr) => {
return superagent.get(unsplashURL).then((unsplashRes) => {
let unsplashBody = unsplashRes.body.results;
let unsplashArray = unsplashBody.map(item => {
return new Ideas(item);
})
unsplashArray.forEach((item) => fullArr.push(item))
return fullArr;
})
}).then((fullArr) => {
if (apiSelect === 'pixabay') {
let pixaBay = fullArr.slice(0, 20);
response.render('pages/results', { keyPhoto: pixaBay });
} else if (apiSelect === 'unsplash') {
let unsplash = fullArr.slice(20, 30);
response.render('pages/results', { keyPhoto: unsplash });
} else if (searchType === 'video') {
superagent.get(videoURL)
.then((videoRes) => {
let videoData = videoRes.body.hits;
let videoDataArray = videoData.map((data) => {
return new Videos(data);
})
videoDataArray.forEach((item) => fullArr.push(item))
response.render('pages/results', { keyPhoto: videoDataArray })
})
} else if (searchType === 'image') {
let fullArr2 = fullArr.slice(0, 30);
response.render('pages/results', { keyPhoto: fullArr2 });
} else {
response.render('pages/results', { keyPhoto: fullArr });
}
})
.catch(error => {
response.render('pages/error');
});
});
///////////////////////saved ideas from search page////////////////////////////////////////
app.post('/search/add', (req, res) => {
console.log(req.body.imgHid);
let { imgHid, titleHid, creatorHid, categoriesHid, sourceHid, likesHid } = req.body;
let searchSQL = 'SELECT * FROM savedIdeas WHERE source_url=$1'
let searchVal = [sourceHid];
client.query(searchSQL, searchVal).then((searchResult) => {
if (searchResult.rows.length === 0) {
console.log('hi')
let SQL = 'INSERT INTO savedIdeas (img_url,title,creator_name,categories,source_url,likes) VALUES ($1,$2,$3,$4,$5,$6);';
let safeValues = [imgHid, titleHid, creatorHid, categoriesHid, sourceHid, likesHid];
return client.query(SQL, safeValues)
.then(() => {
res.status(200).json({ status: 'done' });
})
} else {
res.status(200).json({ status: 'done' });
}
})
})
/*******************************************update******************************************** */
app.put('/saved/update', updateSaved);
function updateSaved(req, res) {
console.log('Hi', req.body.scoreEdit)
let { titleEdit, categEdit, scoreEdit, noteEdit, itemID } = req.body;
let sqlUpdate = 'UPDATE savedIdeas SET title=$1, categories=$2, scoreOfTen=$3, notes=$4 WHERE id=$5';
let updateVal = [titleEdit, categEdit, scoreEdit, noteEdit, itemID];
client.query(sqlUpdate, updateVal).then((updateRes) => {
let updatedNoteAndScore = 'SELECT notes, scoreOfTen FROM savedIdeas WHERE id=$1'
let noteAndScoreVal = [itemID]
client.query(updatedNoteAndScore, noteAndScoreVal).then((noteAndScoreRes) => {
console.log('hey', noteAndScoreRes.rows[0].scoreoften);
res.redirect('/saved');
})
})
}
/********************************************Delete*********************************************/
app.delete('/saved/delete', deleteSaved);
function deleteSaved(req, res) {
let { itemID } = req.body;
console.log(itemID);
let sqlDelete = 'DELETE FROM savedIdeas WHERE id=$1';
let deleteValues = [itemID];
client.query(sqlDelete, deleteValues)
.then(() => {
res.redirect('/saved');
})
}
/////////////////////////////////home page/////////////////////////////////////////////////////
app.get('/', topten);
function topten(req, res) {
let topArray = [];
let key = process.env.PIXABAY_API_KEY;
let pixUrl = `https://pixabay.com/api/?key=${key}&q=design`;
let unsplashKey = process.env.UNSPLASH_KEY;
let unsplashURL = `https://api.unsplash.com/search/photos?query=design&client_id=${unsplashKey}`
superagent.get(pixUrl)
.then(pixRes => {
let pixData = pixRes.body.hits.map((element) => {
return new Photos(element)
})
let sortPixData = pixData.sort((a, b) => {
return b.likes - a.likes
})
let top = sortPixData.slice(0, 6)
top.forEach((item) => topArray.push(item))
return (topArray);
}).then((topArray) => {
superagent.get(unsplashURL)
.then((unsplashRes) => {
const unsplashBody = unsplashRes.body.results;
const unsplashData = unsplashBody.map(item => {
return new Ideas(item);
})
let sortUnsData = unsplashData.sort((a, b) => {
return b.likes - a.likes
})
let final = sortUnsData.slice(0, 6)
final.forEach((item) => topArray.push(item))
return topArray;
}).then((topArray) => {
res.render('pages/index', { photos: topArray })
}).catch(error => {
res.render('pages/error');
});
})
}
/////////////////////saved ideas from home page////////////////////////////////////////////////////
app.post('/', saveidea);
function saveidea(req, res) {
let img_url = req.body.img_url;
let title = req.body.title;
let likes = req.body.likes;
let creator_name = req.body.creator_name;
let categories = req.body.categories;
let source_url = req.body.source_url;
let SQLmainsearch = 'SELECT * FROM savedIdeas WHERE source_url=$1 ;';
let searchValMain = [source_url];
client.query(SQLmainsearch, searchValMain)
.then((mainResult) => {
if (mainResult.rows.length === 0) {
let SQL = 'INSERT INTO savedIdeas (img_url,title,creator_name,categories,source_url,likes) VALUES ($1,$2,$3,$4,$5,$6);';
let saveValues = [img_url, title, creator_name, categories, source_url, likes];
return client.query(SQL, saveValues)
.then(() => {
res.status(200).json({ status: 'done' });
// res.redirect('/saved');
})
} else {
res.status(200).json({ status: 'done' });
}
})
}
app.get('/saved', save);
function save(req, res) {
let SQL = 'SELECT * FROM savedIdeas;';
client.query(SQL)
.then(result => {
res.render('pages/saved', { data: result.rows });
});
}
///////////////////constructor/////////////////////////////////////////////////////
function Photos(data) {
this.title = data.tags;
this.creator_name = data.user;
this.categories = data.type;
this.source_url = data.pageURL;
this.likes = data.likes;
this.img_url = data.largeImageURL;
}
function Ideas(item) {
this.title = item.tags[1].title
this.creator_name = item.user.name;
this.categories = (item.type ? item.type : 'photo');
this.source_url = (item.user.portfolio_url ? item.user.portfolio_url : item.urls.full);
this.likes = item.likes;
this.img_url = item.urls.full;
}
function Videos(item) {
this.title = item.tags;
this.creator_name = item.user;
this.categories = item.type;
this.source_url = item.pageURL;
this.likes = item.likes;
this.img_url = item.videos.medium.url;
}
/////////////////////////////////////////////////////////////////////////////////////////
client.connect().then(() => {
app.listen(PORT, () => console.log('up and running in port', PORT));
});
// handler functions
app.use('*', notFoundHandler);
function notFoundHandler(request, response) {
response.status(404).send('Not Found');
}
function errorHandler(error, request, response) {
response.status(500).send(error);
}