-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
63 lines (55 loc) · 1.86 KB
/
app.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
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt');
const cors = require('cors');
const { connectToDatabase, toFormattedDate } = require('./utils');
const { checkContentType, checkRequestDate, checkRequiredBody, checkValidData, checkEmailExist, checkIfUserExists } = require('./middleware');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(express.static('static'));
app.get('/healthcheck', (req, res) => {
res.send('OK');
});
app.get('/users/:id', [checkContentType, checkRequestDate, checkIfUserExists], (req, res) => {
res.status(200).json({
data: {
user: {
id: req.params.id,
name: req.name,
email: req.email
},
"request-date": req.requestDate
}
});
});
app.post('/users', [checkContentType, checkRequestDate, checkRequiredBody, checkValidData, checkEmailExist], async (req, res) => {
try {
const { name, email, password } = req.body;
const encryptedPwd = await bcrypt.hash(password, 10);
const dbDate = toFormattedDate(req.requestDate);
const data = {
name: name,
email: email,
password: encryptedPwd,
created_at: dbDate
};
const db = await connectToDatabase();
const [rows] = await db.query('INSERT INTO user SET ?', data);
res.status(200).json({
data: {
user: {
id: rows.insertId,
name: name,
email: email
},
"request-date": req.requestDate
}
});
} catch(err) {
return res.status(500).json({ error: 'Error inserting data.' });
}
});
app.listen(3000, () => {
console.log('listening on port 3000');
});