-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
104 lines (86 loc) · 2.46 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
94
95
96
97
98
99
100
101
102
103
104
if(process.env.NODE_ENV !== 'production'){
require('dotenv').config()
}
const express = require("express")
const mongoose = require('mongoose')
const app = express()
const validUrl = require('valid-url')
const shortid = require('shortid')
const url = require('./models/UrlModel')
// Database config
try {
// Connect to the MongoDB cluster
mongoose.connect(
process.env.DATABASE_URI,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => console.log("mongoose is connected")
);
} catch (e) {
console.log("could not connect");
}
const dbConnection = mongoose.connection;
dbConnection.on("error", (err) => console.log(`Connection error ${err}`));
dbConnection.once("open", () => console.log("Connected to DB!"));
// Routes Config
app.use(express.json({
extended: false
}))
//const baseUrl = 'http:localhost:5000'
const baseUrl = 'https://hotlink.herokuapp.com'
app.get('/',(req,res)=>{
console.log('requested')
res.send("Hello there!")
})
app.post('/url/shorten', async(req,res)=>{
const {longUrl}=req.body
if(!validUrl.isUri(baseUrl)){
return res.status(401).json('Invalid base URL')
}
// create url code
const urlCode = shortid.generate()
//check long url
if(validUrl.isUri(longUrl)){
try{
let single_url = await url.findOne({longUrl})
if(single_url){
res.json(single_url)
}
else{
const shortUrl = baseUrl + '/'+ urlCode
single_url = new url({
longUrl,
shortUrl,
urlCode,
date: new Date()
})
await single_url.save()
res.json(single_url)
}
}
catch(err){
console.log(err)
res.status(500).json('Server Error')
}
}
else{
res.status(401).json('Invalid longUrl')
}
})
app.get('/:code',async(req,res)=>{
try{
const single_url = await url.findOne({urlCode: req.params.code})
if(single_url){
return res.redirect(single_url.longUrl)
}
else{
return res.status(404).json('No URL Found')
}
}
catch(err){
console.error(err)
res.status(500).json('Server Error')
}
})
//Listen for incoming requests
const PORT = process.env.PORT || 3000
app.listen(PORT, console.log(`server started, listening PORT ${PORT}`))