-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyApp.js
74 lines (68 loc) · 2.11 KB
/
myApp.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
var express = require("express")
var app = express()
var bodyParser = require("body-parser")
var fs = require("fs")
var dns = require("dns")
var url = require("url")
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", (req, res) => {
res.send("hi")
})
app.get("/api/shorturl/:num", (req, res) => {
if (!req.params.num){
return res.json({"error":"no url specified"})
}
var rawData = fs.readFileSync('./urls.json');
var json = JSON.parse(rawData);
var url = json.list[req.params.num]
if (req.params.num > json.list.length - 1 || req.params.num < 0){
return res.json({"error":"specified shortened URL is not valid"})
}
console.log(url)
res.redirect(url);
})
app.post(
"/api/shorturl/new",
(req, res) => { // check json file for matching url
if (!req.body.url){
console.log(err);
return res.json({error: "invalid URL"})
}
var parsedURL = url.parse(req.body.url)
console.log(parsedURL);
if (parsedURL.protocol == null){
return res.json({"error": "invalid URL"})
}
dns.lookup(parsedURL.host, (error, address, family) => {
console.log(address, family)
if (error){
return res.json({"error": "invalid URL"})
}
})
var rawData = fs.readFileSync('./urls.json');
var json = JSON.parse(rawData);
var index = json.list.indexOf(parsedURL.href)
if (index > -1){
console.log("have this url")
return res.json({
orignal_url:parsedURL.href,
short_url: index
})
} else {
json.list.push(parsedURL.href)
fs.writeFile('urls.json', JSON.stringify(json), 'utf8', (err)=>{
if (err){
return res.json({"error":"no idea what went wrong"})
}
res.json({
orignal_url:req.body.url,
short_url:json.list.length - 1
});
})
}
}
)
module.exports = app