-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
56 lines (47 loc) · 1.47 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
const express = require('express');
const {connectToMongoDb} = require('./connect');
const {checkForAuthentication, restrictTo} = require('./middlewares/auth');
const URL = require('./modals/url');
const urlRoute = require('./routes/url');
const path = require('path');
const cookieParser = require('cookie-parser');
const staticRouter = require('./routes/staticRouter');
const UserRoute = require('./routes/user');
const { userInfo } = require('os');
const app = express();
const PORT = 3000;
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.use(cookieParser());
app.use(checkForAuthentication);
app.set('view engine','ejs');
app.set('views' ,path.resolve('./views'));
app.get('/test',async(req,res)=>{
const allUrls = await URL.find({});
return res.render('home',{
urls: allUrls,
});
})
app.use('/',staticRouter);
app.use('/url',restrictTo(['NORMAl','ADMIN']),urlRoute);
app.use('/user',UserRoute);
app.get('/:shortId',async (req,res)=>{
const shortId = req.params.shortId;
const entry = await URL.findOneAndUpdate({
shortId
}, {
$push: {
visitHistory:{
timestamp : Date.now()
}
}
}
);
if(entry){
res.redirect(entry.redirectUrl);
}else{
return res.status(404).send('URL not found');
}
});
app.listen(PORT,()=>console.log(`server started at port:${PORT}`));
connectToMongoDb('mongodb://127.0.0.1:27017/short-url',()=> console.log('mongoDb connected'));