-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
79 lines (60 loc) · 1.71 KB
/
server.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
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const dns = require("dns");
const url = require("url");
const mongoose = require("mongoose");
const app = express();
// Basic Configuration
const port = process.env.PORT || 3000;
app.use(cors());
app.use("/public", express.static(`${process.cwd()}/public`));
app.use(express.urlencoded({ extended: false }));
app.get("/", function (req, res) {
res.sendFile(process.cwd() + "/views/index.html");
});
// Your first API endpoint
app.post("/api/shorturl", function (req, res) {
const { url } = req.body;
let myURL;
try {
myURL = new URL(url);
} catch {
return res.json({ error: "invalid url" });
}
const { protocol } = myURL;
if (protocol !== "http:" && protocol !== "https:") {
return res.json({ error: "invalid url" });
}
const docsCount = await Address.estimatedDocumentCount();
let address = await Address.findOne({ originalUrl: url });
if (!address) {
address = new Address({ originalUrl: url, shortUrl: docsCount + 1 });
await address.save();
}
res.json({ original_url: address.originalUrl, short_url: address.shortUrl });
});
app.get("/api/shorturl/:shorturl", async (req, res) => {
const { shorturl } = req.params;
const address = await Address.findOne({ shortUrl: shorturl });
if (!address) {
res.json({ error: "No short URL found for the given input" });
}
res.redirect(address.originalUrl);
});
mongoose.connect(
process.env.DB_URI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
},
err => {
if (err) {
console.log(err);
} else {
app.listen(port, function () {
console.log(`Listening on port ${port}`);
});
}
}
);