-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
102 lines (91 loc) · 3.22 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
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
95
96
97
98
99
100
101
102
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var linkRouter = require('./routes/Links');
var userActionsRouter = require('./routes/UserAction');
var userAuthRouter = require('./routes/UserAuth');
var recoveryRouter = require('./routes/Recovery');
const cors = require('cors');
var app = express();
const sendOTP = require('./routes/sendOTP')
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// Set the allowed origin and credentials
const corsOptions = {
origin: 'http://localhost:3000',
credentials: true,
};
app.use(cors(corsOptions));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Database connection setup
const MongoClient = require('mongodb').MongoClient;
const dotenv = require('dotenv');
dotenv.config();
const connString = process.env.MONGO_CONNECTION_STRING;
let db; // Declare a variable to store the database connection
let dbReady = false; // Flag to indicate if the database connection is ready
// Function to establish the database connection
async function connectToDB() {
try {
const client = await MongoClient.connect(connString, { useNewUrlParser: true, useUnifiedTopology: true });
console.log("Connected To Db");
db = client.db('urlpro'); // Store the connection in the db variable
dbReady = true; // Set the flag to true once the connection is established
} catch (err) {
console.log(err);
}
}
// Call the connectToDB function to establish the connection when the application starts
connectToDB();
// Middleware to attach the database connection to the request object
app.use(async (req, res, next) => {
if (dbReady) {
req.db = db; // Reuse the existing connection
next();
} else {
// Wait until the database connection is ready before proceeding to the next middleware
const checkDBReady = () => {
if (dbReady) {
req.db = db; // Reuse the existing connection
next();
} else {
setTimeout(checkDBReady, 100); // Check again after a short delay
}
};
checkDBReady();
}
});
app.use('/static', express.static(path.join(__dirname, 'static')));
app.use('/auth', userAuthRouter);
app.use('/user', userActionsRouter);
app.use('/forgot', recoveryRouter);
app.use('/links', linkRouter);
app.post("/sendEmail",async function(req,res){
if(req.headers.email && req.headers.otp){
const send = await sendOTP(req.headers.otp,req.headers.email)
res.json({message:"email sent success "})
}else{
res.status(404).json({message:"Please pass email and otp in body"})
}
})
app.get("/",(req,res)=>{
res.redirect('https://documenter.getpostman.com/view/25483510/2s9Y5ZwMti#intro')
})
app.get("/:endpoint",async function(req,res){
const endpoint = req.params.endpoint;
const links = req.db.collection("links")
const link = await links.findOneAndUpdate({endpoint:endpoint},{$inc:{views:1}})
if(link.value === null){
res.redirect("https://urlpro.vercel.app");
}else{
res.redirect(link.value.url);
}
})
module.exports = app;