-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
83 lines (60 loc) · 2.02 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
80
81
82
83
'use strict';
var express = require('express');
var mongoose = require('mongoose');
const dns = require('dns');
const Ruler = require('url');
var cors = require('cors');
var app = express();
// Basic Configuration
var port = process.env.PORT || 3000;
/** this project needs a db !! **/
mongoose.connect("mongodb+srv://quocviet:quocviet@vidly-2mbqg.mongodb.net/url-shortener?retryWrites=true&w=majority", { useUnifiedTopology: true, useNewUrlParser: true });
const Url = mongoose.model('url', new mongoose.Schema({
"original_url": String,
"short_url": Number
}));
app.use(cors());
/** this project needs to parse POST bodies **/
// you should mount the body-parser here
app.use('/public', express.static(process.cwd() + '/public'));
app.use(express.urlencoded());
app.get('/', function (req, res) {
res.sendFile(process.cwd() + '/views/index.html');
});
// your first API endpoint...
app.get("/api/hello", function (req, res) {
res.json({ greeting: 'hello API' });
});
app.get('/api/shorturl/:id', async (req, res) => {
const packedUrl = await Url.findOne({ short_url: req.params.id });
if (!packedUrl) return res.status(404).send("No shortened url found.");
res.redirect(packedUrl.original_url);
});
app.post("/api/shorturl/new", async (req, res) => {
const url_string = Ruler.parse(req.body.url);
if (!url_string.protocol || !url_string.hostname) return res.json({ error: "invalid URL" });
dns.lookup(url_string.hostname, async (error) => {
if (error) {
return res.json({ error: "invalid URL" });
}
let url = await Url.findOne({ "original_url": req.body.url });
if (url) {
return res.json({
original_url: url.original_url,
short_url: url.short_url
});
}
url = new Url({
original_url: req.body.url,
short_url: Math.floor(Math.random() * 999)
});
await url.save();
return res.json({
original_url: url.original_url,
short_url: url.short_url
})
});
})
app.listen(port, function () {
console.log('Node.js listening ...');
});