-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
72 lines (62 loc) · 2.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
require("dotenv").config();
const express = require('express');
const path = require('path');
const cors = require('cors');
const Participant = require('./models/Participant');
const mongoose = require("mongoose");
const {check, validationResult} = require('express-validator');
mongoose.connect(process.env.MONGO_URI)
.catch((error) => {
console.log("Connection to database failed:", error);
})
.then(() => {
console.log("Successfully connected to database");
});
const app = express();
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());
app.use(express.urlencoded({extended: true}));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '/index.html'));
})
app.post('/participants', [
check('email', 'email is required !').not().isEmpty(),
check('email', 'Invalid email !').isEmail().isLength({ min: 10, max: 30 }),
check('fullname', 'fullname is required !').not().isEmpty(),
check('fullname', 'Please enter your real name !').isLength({ min: 5, max: 50 }),
check('motivation', 'Motivation is required !').not().isEmpty(),
// check('motivation', 'FirstName length should be 3 to 30 characters').isLength({ min: 5, max: 50 }),
// check('lastname', 'Lastname is required').not().isEmpty(),
// check('lastname', 'LastName length should be 3 to 30 characters')
// .isLength({ min: 3, max: 30 })
],
async (req, res, next) => {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) return res.status(200).json({err: true, errors: errors.errors});
const exists = await Participant.findOne({ email : req.body.email }).exec();
if(exists) return res.status(200).json({err: true, errors: [{msg: 'Email already registered !'}]});
const newParticipant = new Participant({
email: req.body.email.toLowerCase(),
fullname: req.body.fullname.toLowerCase(),
// lastname: req.body.lastname.toLowerCase(),
speciality: req.body.speciality.toLowerCase(),
level: req.body.level.toLowerCase(),
discord: req.body.discord.toLowerCase(),
motivation: req.body.motivation.toLowerCase()
});
const result = await newParticipant.save();
if(result) return res.status(200).json({err: false, msg: 'Successfully registered !'});
return res.status(200).json({err: true, errors: [{msg: 'Something went wrong !'}]});
}
catch( err )
{
console.log('something went wrong : ' + err.message);
return res.status(200).json({err: true, errors: [{msg: 'Something went wrong !'}]});
}
});
const PORT = process.env.PORT || 3003;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});