-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
197 lines (149 loc) · 5.28 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
'use strict';
// =================== Packages ===================== //
const express = require('express');
const superagent = require('superagent');
const pg = require('pg');
const methodOverride = require('method-override');
const { query } = require('express');
require('dotenv').config();
// =================== Global Variables ===================== //
const PORT = process.env.PORT || 3003;
const app = express();
const DATABASE_URL = process.env.DATABASE_URL;
const IMAGGA_AUTH_ID = process.env.IMAGGA_AUTH_ID;
const IMAGGA_AUTH_SECRET = process.env.IMAGGA_AUTH_SECRET;
// ================= Configs ====================//
app.use(express.static('./public'));
app.use(express.urlencoded({extended: true}));
app.set('view engine', 'ejs');
const client = new pg.Client({
connectionString: DATABASE_URL,
ssl: {
rejectUnauthorized: false
}
});
client.on('error', (error) => console.error(error));
app.use(methodOverride('_method'));
// ===================== Routes ======================= //
app.get('/', homePage);
app.get('/gallery', renderGallery);
app.get('/favorites', renderDB);
app.get('/aboutus', renderAboutUs);
app.post('/gallery', saveInfo);
// ========================== Route Handlers ============================ //
function homePage (req, res) {
const apiQuery = `http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en`;
superagent.get(apiQuery)
.then(result => {
const quote = new Quotes(result);
res.render('pages/index', {data: quote});
})
// a manual quote will populate if the API gives error
.catch(()=> {
const quote = {text:'Catching errors like a fisherman catches fish.', author: 'Tif Taylor'};
res.render('pages/index', {data: quote});
})
.catch(error => errorHandler(error, res));
}
function renderGallery (req, res) {
// --- query to get objectIds -- //
const apiQuery = `https://collectionapi.metmuseum.org/public/collection/v1/search?departmentId=6&q=color`;
// -- first superagent call to get ID array -- //
superagent.get(apiQuery)
.then(result => {
const idArray = result.body.objectIDs;
let arrRandom = [];
while (arrRandom.length < 20){
const randomIndex = idArray[Math.floor(Math.random()*idArray.length) + 1];
if(arrRandom.indexOf(randomIndex) === -1 ) arrRandom.push(randomIndex);
}
let promiseArr = [];
arrRandom.forEach(value => {
const objectId = value;
const apiQueryObject = `https://collectionapi.metmuseum.org/public/collection/v1/objects/${objectId}`;
promiseArr.push(superagent.get(apiQueryObject));
});
Promise.all(promiseArr).then(values => {
return values.map(val => {
const constructedObj = new Image (val);
return constructedObj;
});
})
.then(vals => {
res.render('pages/gallery', {dataArray: vals});
});
})
.catch(error => errorHandler(error, res));
}
function renderDB (req, res) {
client.query('SELECT * FROM faves')
.then(dbResult => {
const dbData = dbResult.rows;
// sorts array to display most recent save at the top
dbData.sort((a,b) => b.id - a.id);
res.render('pages/favorites', {
dataArray: dbData
});
})
.catch(error => errorHandler(error, res));
}
function saveInfo (req, res) {
// get image info from POST body
const { img, title, artist } = req.body;
// use image to get colors from API
const url = 'https://api.imagga.com/v2/colors';
const query = {image_url: img};
superagent.get(url)
.auth(IMAGGA_AUTH_ID, IMAGGA_AUTH_SECRET)
.query(query)
.then(colorResponse => {
console.log(`retrieved colors for ${title} by ${artist}`);
// construct palette
const colorObjs = colorResponse.body.result.colors.image_colors;
const paletteArr = colorObjs.map( eachObj => eachObj.html_code);
const thisPalette = new Color(paletteArr);
const { color1, color2, color3, color4 } = thisPalette;
// insert image info and its palette into DB
const sql = 'INSERT INTO faves (title, artist, img, color1, color2, color3, color4) VALUES ($1, $2, $3, $4, $5, $6, $7)';
const valueArr = [title, artist, img, color1, color2, color3, color4];
client.query(sql, valueArr)
.then( () => {
console.log('added art and colors to DB');
res.redirect('/favorites');
});
})
.catch(error => errorHandler(error, res));
}
function renderAboutUs (req, res) {
res.render('pages/about');
}
// =================== Misc. Functions ===================== //
function Image(artObj) {
const art = artObj.body;
this.title = art.title;
this.artist = art.artistDisplayName;
this.img = art.primaryImage;
}
function Quotes(obj) {
const quote = obj.body;
this.text = quote.quoteText;
this.author = quote.quoteAuthor;
}
function Color(colorArr) {
this.color1 = colorArr[0];
this.color2 = colorArr[1];
this.color3 = colorArr[2];
this.color4 = colorArr[3];
}
function errorHandler(error, res) {
console.log(error);
res.status(500).render('pages/error', {
status: 500,
message: error.message
});
}
// =================== Start Server ===================== //
client.connect()
.then(() => {
app.listen(PORT, () => console.log('you\'re connected'));
});