-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
70 lines (55 loc) · 1.66 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
const express = require("express");
let mongoose = require("mongoose");
var bodyParser = require("body-parser");
require("dotenv").config();
const app = express();
const cors = require('cors')
app.use(cors())
app.use(express.json())
app.use(bodyParser.urlencoded({ extended: false }));
// app.get('/', (req, res) => res.send('Hello World!'));
mongoose
.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(console.log("DB Connected"));
function generateRandomString(length) {
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let randomString = "";
for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * characters.length);
randomString += characters.charAt(randomIndex);
}
return randomString;
}
let URLSchema = mongoose.Schema({
url: { type: String },
short: { type: String },
});
let URL = mongoose.model('url', URLSchema);
app.post("/create", async (req, res) => {
const short = generateRandomString(5);
const url = req.body.url;
const newURL = new URL({ url: url, short: short });
try {
await newURL.save();
res.json(newURL);
} catch (error) {
console.error(error);
res.status(500).json({ error: "An error occurred while saving the URL." });
}
});
app.get('/:url',(req,res)=>{
const url = req.params.url;
// console.log(url);
URL.findOne({short: url}).then((data)=>{
res.json({url: data.url})
}).catch(
(err)=>{
res.json({error: "URL not found"})
}
)
})
app.listen(process.env.PORT || 3000, () => console.log("Started"));