-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
94 lines (81 loc) · 2.45 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
require('dotenv').config();
// express
const express = require('express');
const bodyParser = require('body-parser');
const Router = require('express-promise-router');
const app = express();
const router = new Router();
app.use(bodyParser.json());
const path = require('path');
// postgress
const { Pool } = require('pg');
const connectionString = process.env.DB_URL;
const pool = new Pool({ connectionString });
const query = (text, params) => pool.query(text, params);
// validation
const Joi = require('joi');
/**
* ordersSchemaIsInvalid
*
* @returns {null} or an {object} containing validation error details
*/
const ordersSchemaIsInvalid = ({ surveyData }) => {
const restaurantNamePattern = /\[.+\]/;
const orderSchema = Joi.object().keys({
Timestamp: Joi.date().required(),
'Email Address': Joi.string().email().required(),
meal: Joi.string().min(5).regex(restaurantNamePattern).required(),
});
const ordersSchema = Joi.array().items(orderSchema);
return Joi.validate(surveyData, ordersSchema, {
allowUnknown: true,
}).error;
};
/**
orders table is like this, for now title, and archived are note used
CREATE TABLE orders (
ID serial NOT NULL PRIMARY KEY,
title VARCHAR (100),
survey_data jsonb NOT NULL,
created_at timestamptz default now() not null,
archived boolean DEFAULT false,
username VARCHAR
);
*/
app.post('/api/survey-data/add', async (req, res) => {
const { surveyData } = req.body;
const user = req.headers["remote-user"] || 'unknown';
const validationError = ordersSchemaIsInvalid({ surveyData });
if (!surveyData || validationError) {
res.status(400).send(validationError);
}
try {
const {
rows,
} = await query(
'INSERT INTO orders (survey_data, username) VALUES ($1, $2) RETURNING id',
[JSON.stringify(surveyData), user],
);
res.send(rows[0]);
} catch (e) {
res.status(500).send(e);
}
});
app.get('/api/survey-data/latest', async (req, res) => {
try {
const { rows } = await query(
'SELECT survey_data, created_at, username FROM orders ORDER by id desc LIMIT 1',
);
res.send(rows[0]);
} catch (e) {
res.status(500).send(e);
}
});
app.use(express.static(path.resolve(__dirname, 'build')));
// Always return the main index.html
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'build', 'index.html'));
});
const server = app.listen(8000, () => {
console.log('server started on: ', server.address().port);
});