-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
68 lines (58 loc) · 1.94 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
/**
* URL Shortener
* Copyright (C) 2022, Adriane Justine Tan
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
const path = require('path')
const express = require('express')
const cors = require('cors')
const { Client } = require('pg')
const dbMiddleware = require('./server/database')
const shorts = require('./server/shorts/')
const redirect = require('./server/redirect')
const port = process.env.PORT || 8082
const app = express()
const clientConfig = {
application_name: 'URL Shortener',
ssl: { rejectUnauthorized: false }
}
if (typeof process.env.DATABASE_URL === 'string') {
clientConfig.connectionString = process.env.DATABASE_URL
}
const client = new Client(clientConfig)
client.connect()
app.use(cors())
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use('/', express.static('build'))
app.use('/api/shorts', dbMiddleware(client), shorts)
app.use('/r/', dbMiddleware(client), redirect)
app.use('/*', (req, res) => {
const indexPath = path.resolve(__dirname, 'build', 'index.html')
res.sendFile(indexPath)
})
const server = app.listen(port, () => {
console.log(`Server is running on port ${port}`)
})
server.on('close', async () => {
console.log('Server is closing...')
client.end()
})
process.on('SIGINT', () => {
server.close(() => {
console.log('Exiting process...')
process.exit(0)
})
})