-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
106 lines (91 loc) · 2.44 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// add diff
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const md5 = require('md5')
const path = require('path')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
next()
})
app.use(express.static(path.resolve(__dirname, '.', 'build')))
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, '.', 'build', 'index.html'))
})
app.set('port', process.env.PORT || 3000)
app.locals.title = 'Jet Fuel'
const environment = process.env.NODE_ENV || 'development'
const configuration = require('./knexfile')[environment]
const database = require('knex')(configuration)
app.get('/api/folders', (req, res) => {
database('folders').select()
.then((folders) => {
res.status(200).json(folders)
})
.catch((err) => {
console.error(err)
})
})
app.get('/api/urls', (req, res) => {
database('urls').select()
.then((urls) => {
res.status(200).json(urls)
})
.catch((err) => {
console.error(err)
})
})
app.get('/:shortUrlId', (req, res) => {
const { shortUrlId } = req.params
database('urls').select()
.then(urls => urls.filter(urlContent => urlContent.id.slice(0, 5) === shortUrlId))
.then((targetUrl) => res.redirect(targetUrl[0].long_url))
})
app.post('/api/folders', (req, res) => {
const { name } = req.body
const id = md5(name)
const folderContent = {
id,
name,
created_at: new Date()
}
database('folders').insert(folderContent)
.then(() => {
database('folders').select()
.then((folders) => {
res.status(200).json(folders)
})
})
.catch((err) => {
console.error(err)
})
})
app.post('/api/urls', (req, res) => {
const { long_url, folder_id } = req.body
const id = md5(long_url)
const short_url = id.slice(0, 5)
const urlContent = {
id,
long_url,
short_url,
popularity: 0,
folder_id,
created_at: new Date()
}
database('urls').insert(urlContent)
.then(() => {
database('urls').select()
.then((urls) => {
res.status(200).json(urls)
})
})
.catch((err) => {
console.error(err)
})
})
app.listen(app.get('port'), () => {
console.log(`${app.locals.title} is running on ${app.get('port')}.`)
})