-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
46 lines (40 loc) · 1003 Bytes
/
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
const console = require('console')
const express = require('express')
const bodyParser = require('body-parser')
const { getUrl, storeUrl } = require('./models')
const app = express()
const PORT = 8080
app.use(express.static('public'))
app.use(bodyParser.json())
app.get('/:hash', (req, res) => {
const { hash } = req.params
getUrl(hash, (err, url) => {
if (err) {
res.status(404).json({
error: 'Unable to redirect'
})
} else {
link = url.includes('https') ? url : url.includes('http') ? url : `http://${url}`
res.status(307).redirect(link)
}
})
})
app.post('/shorten', (req, res) => {
const { url } = req.body
storeUrl(url, (err, hash, _url) => {
if (err) {
// todo: add error handling
res.status(500).send({
error: 'Unable to shorten URL'
})
} else {
res.json({ status: 'success',
hash,
_url
})
}
})
})
app.listen(PORT, () => {
console.log(`listening on port ${PORT}`)
})