-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
93 lines (82 loc) · 2.51 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
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
const express = require('express');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 5000;
const http = require('http').Server(app);
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const nanoid = require('nanoid');
const uri = "mongodb+srv://rahulanand16nov:Password@shortttycluster-nmp49.mongodb.net/test?retryWrites=true&w=majority";
MongoClient.connect(uri,{useNewUrlParser: true, useUnifiedTopology: true},(error, client) => {
if(error) {
throw error;
}
console.log("YEA");
database = client.db('shortttydb');
urlsCollection = database.collection("urls");
});
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
// NEED TO BE FIXED
/* function newID(shortid){
urlsCollection.find({shortID:shortid}).toArray(function(error,document){
if(error) throw error;
// If ID is already used
if(document.length!==0){
shortid = nanoid(6);
return shortid;
} else {
return shortid;
}
})}; */
// API Endpoint for creating URL
app.post('/createURL',(req,res)=>{
let ogURL;
try{
ogURL = new URL(req.body.ogURL);
} catch (err){
return res.send(err);
}
// If given URL already exists or not
urlsCollection.find({originalURL:ogURL.href}).toArray(function(error,document){
if(error) throw error;
// Already in DB
if(document.length!==0){
res.send(document);
} else
{
// Given URL is not in the database so inserting it now
let shortid = nanoid(6);
//shortid = newID(shortid);
urlsCollection.insertOne({originalURL:ogURL.href,shortID:shortid},(error,result)=>
{
if(error)
{
return res.status(500).send(error);
}
urlsCollection.find({originalURL:ogURL.href}).toArray(function(error,document){
if(error) throw error;
res.send(document);
});
});
}
});
});
// API endpoint to redirect
app.get("/:shortID",(req,res)=>{
const shortid = req.params.shortID;
console.log(shortid);
urlsCollection.find({shortID:shortid}).toArray(function(error,document){
if(error) throw error;
if(document.length===0){
res.send("URL not found");
} else {
res.redirect(document[0].originalURL);
}
});
});
http.listen(PORT, () => console.log(`Listening on ${ PORT }`));
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', (req, res) => res.render('index'));