-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
68 lines (57 loc) · 1.99 KB
/
index.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
const config = require('./config.js');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const moment = require('moment');
////// MIDDLEWARE //////
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.set('views', './www');
////// DATABASE //////
mongoose.connect(config.mongoUrl, { useNewUrlParser: true });
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('Connected to MongoDB');
});
let textSchema = new mongoose.Schema({
name: String,
text: String,
updated_at: { type: String, default: moment().format('DD/MM/YYYY HH:mm:ss') },
createDate: { type: String, default: moment().format('DD/MM/YYYY HH:mm:ss') }
});
let Text = mongoose.model('Text', textSchema);
////// ROUTES GET //////
app.get('/', async (req, res) => {
let shares = await Text.find({}).sort({_id: -1});
res.render('index.ejs', { config, shares });
});
app.get('/show/:id', async (req, res) => {
if(!req.params.id) return res.status(400).send('No ID provided');
let text = await Text.findOne({ _id: req.params.id });
if(!text) return res.status(404).send('No text found');
res.render('show.ejs', { config, text });
});
////// ROUTES POST //////
app.post('/create', async (req, res) => {
const { name, text } = req.body;
if (!name || !text) {
return res.status(400).json({ error: 'Missing required fields' });
}
let newText = new Text({
name,
text
});
try {
newText = await newText.save();
return res.redirect(`/show/${newText._id}`);
} catch (err) {
return res.status(500).json({ error: err.message });
}
});
////// SERVER //////
app.listen(config.port, () => {
console.log(`Example app listening on port ${config.port}!`);
});