/
server.js
293 lines (244 loc) · 8.74 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
'use strict';
require('dotenv').config();
require('ejs');
// ------------ DEPENDENCIES --------------
const pg =require('pg');
const cors = require('cors');
const express = require('express');
const superagent = require('superagent');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const methodOverride = require('method-override');
const { request } = require('http');
// ------------- CONFIG -------------------
const app = express();
const client = new pg.Client(process.env.DATABASE_URL);
app.use(cors());
app.use(express.static('./public'));
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(methodOverride('_method'));
const PORT = process.env.PORT;
const TEMPLATE_FORM = process.env.TEMPLATE_FORM;
app.set('view engine', 'ejs');
// -------------- ROUTES ------------------
app.get('/login', loginPage);
app.get('/login/session', loginSessionAuto);
app.post('/login/session', loginSessionManual);
app.get('/admin', adminPage);
app.delete('/delete/:id', deleteSurvey);
app.get('/result/:id', showResult);
app.get('/database/:id', showDatabase);
app.post('/survey/create', createSurvey);
app.get('/survey/:id', doSurvey);
app.post('/past_results', showPastResults);
app.delete('/database/:id', deleteDatabase);
app.get('/past_results', showPastResults);
// -------------- CONSTRUCTORS ------------------
function Form(trueAnswer, obj) {
this.username = obj.username;
this.survey_id = obj.id;
this.created_at = obj.created_at;
this.count = obj.count;
this.true_answer = trueAnswer;
}
// -------- LOGIN ROUTES ------------------------------------------
app.get('/', (req, res) => {
if(req.cookies && req.cookies.jotform)
res.redirect('/login/session');
else
res.redirect('/login');
});
function loginPage(req, res) {
res.clearCookie('jotform');
res.render('pages/login');
}
// called when a user inputs their API key from the /login page, and is redirected to /login/session via POST
function loginSessionManual(req, res) {
loginSession(req, res, req.body.key);
}
// called when a user navigates to the / homepage, but is redirected to /login/session via GET
function loginSessionAuto(req, res) {
loginSession(req, res, req.cookies.jotform);
}
// called from either the automatic or the manual login
function loginSession(req, res, key) {
let URL = `https://api.jotform.com/user?apiKey=${key}`;
superagent.get(URL)
.then( () => {
res.cookie('jotform', key);
res.redirect('/admin');
})
.catch( () => {
res.clearCookie('jotform');
res.redirect('/login');
});
}
// -------------- SHOW THE ADMIN PAGE ----------------------------
// we are making an assumption here, that you have a good API key with read/write access
function adminPage(req, res) {
let apiKey = req.cookies.jotform;
let URL = `https://api.jotform.com/user?apiKey=${apiKey}`;
superagent.get(URL)
.then(result => {
let limit = result.body['limit-left'];
console.log('limit: ', limit);
let URL = 'https://api.jotform.com/user/forms';
superagent.get(URL)
.set('APIKEY', apiKey)
.then(result => {
let forms = result.body.content.filter(form => {
if(form.status === 'ENABLED') {
let theForm = new Form(null, form);
return theForm;
}
})
res.render('pages/admin', {forms:forms, limit:limit});
})
.catch(err => console.error(err));
})
.catch(err => console.error(err));
}
// ------- SAVES SURVEY TO DATABASE -------------------
function saveDatabaseDeleteForm(req, res) {
let apiKey = req.cookies.jotform;
let id = req.params.id;
let saveURL = `https://api.jotform.com/form/${id}/submissions?apiKey=${apiKey}`;
let counter = 0;
let surveyResultsString = '';
superagent.get(saveURL)
.then(result => {
let submissions = result.body.content;
// create an array of each persons sum total of TRUE answers
let people = submissions.map( person => {
let keys = Object.keys(person.answers);
return keys.reduce((acc, key)=>{
return acc + (person.answers[key].answer === 'TRUE' ? 1 : 0);
}, 0);
});
let surveyResults = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
// now lets loop through our 'people' array, and increment the corresponing surveyResults
for(let i=0; i<people.length; i++) {
surveyResults[people[i] -1]++;
}
surveyResultsString = surveyResults.join(',');
})
.then(() => {
let URL = 'https://api.jotform.com/user/forms';
superagent.get(URL)
.set('APIKEY', apiKey)
.then(result => {
let array = result.body.content;
let form = '';
array.forEach(index =>{
if (index.id === id) {
form = index;
}
});
let theForm = new Form(counter, form);
let SQL = `INSERT INTO divtech (username, survey_id, created_at, count, true_answer) VALUES ($1, $2, $3, $4, $5);`;
let values = [theForm.username, theForm.survey_id, theForm.created_at, theForm.count, surveyResultsString];
client.query(SQL, values)
.then(results => {
console.log('what is resuslts', results);
})
})
})
}
// ------------ DELETES SURVEY AND SAVES TO DATABASE -----------------
function deleteSurvey(req, res) {
let apiKey = req.cookies.jotform;
let id = req.params.id;
let deleteFormURL = `https://api.jotform.com/form/${id}?apiKey=${apiKey}`;
//----------DELETES FORM SAVES TO DATABASE--------------
saveDatabaseDeleteForm(req,res);
superagent.delete(deleteFormURL)
.then(() => {
res.redirect('/admin');
})
.catch(err => console.error(err));
}
// ------------ SHOW THE GRAPH OF A SURVEY ----------------------
function showResult(req, res) {
let id = req.params.id;
let key = req.cookies.jotform;
let URL = `https://api.jotform.com/form/${id}/submissions?apiKey=${key}`;
// Collect all the submissions for a given form
superagent.get(URL)
.then(result => {
let submissions = result.body.content;
// create an array of each persons sum total of TRUE answers
let people = submissions.map( person => {
let keys = Object.keys(person.answers);
return keys.reduce((acc, key)=>{
return acc + (person.answers[key].answer === 'TRUE' ? 1 : 0);
}, 0);
});
let surveyResults = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
// now lets loop through our 'people' array, and increment the corresponing surveyResults
for(let i=0; i<people.length; i++) {
surveyResults[people[i] -1]++;
}
// pass those results through the page/graph ejs
res.render('pages/graph', { surveyResults : surveyResults });
})
.catch(err => console.error(err));
}
//--------------------SHOW PAST SURVEY RESULTS--------------------
function showDatabase(req, res) {
let SQL = `SELECT true_answer FROM divtech WHERE survey_id=$1;`;
let values = [req.params.id];
client.query(SQL, values)
.then(results => {
res.render('pages/graph', { surveyResults : results.rows[0] });
})
.catch(err => console.error(err));
}
//------------DELETE SURVEY FROM DATABASE------------------------
function deleteDatabase(req, res) {
let SQL = `DELETE FROM divtech WHERE survey_id=$1;`;
let values = [req.params.id];
client.query(SQL, values)
.then(() => {
res.redirect('/past_results');
})
.catch(err => console.error(err));
}
// ------------ CLONE A NEW SURVEY ------------------------------
function createSurvey(req, res) {
let apiKey = req.cookies.jotform;
let URL = `https://api.jotform.com/form/${TEMPLATE_FORM}/clone?apiKey=${apiKey}`
superagent.post(URL)
.then( () => {
res.redirect('/admin');
})
.catch(err => console.error(err));
}
// --------- SHOW LIST OF SURVEYS SAVED IN DATABASE ---------------
function showPastResults(req, res) {
let SQL = `SELECT * FROM divtech WHERE username=$1;`;
let values = [req.body.user];
client.query(SQL, values)
.then(items => {
if( items.rows.length > 0) {
res.status(200).render('pages/past_results', {pastResults: items.rows});
} else {
res.redirect('/admin');
}
})
.catch(err => console.error(err));
}
// ---- DO A SURVEY (this is the route associated with a link that is shared to users) ----
function doSurvey(req, res) {
let id = req.params.id;
res.render('pages/survey', { id : id });
console.log(req.params.id);
}
// ------------ START LISTENING ON A PORT -----------------------
client.connect()
.then(() => {
app.listen(PORT, () => {
console.log(`------- Listening on port : ${PORT} --------`);
});
})