This repository has been archived by the owner on Aug 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
94 lines (86 loc) · 1.83 KB
/
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
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
const express = require('express')
const helmet = require('helmet')
const morgan = require('morgan')
const cors = require('cors')
const monk = require('monk')
const {
nanoid
} = require('nanoid')
const yup = require('yup')
require('dotenv').config()
const app = express()
const schema = yup.object().shape({
url: yup.string().trim().url().required(),
slug: yup.string().trim().matches(/[\w\-]/i)
})
const db = monk(process.env.MONGO_URI)
const wrappers = db.get('wrappers')
wrappers.createIndex({
slug: 1
}, {
unique: true
})
app.use(helmet())
app.use(morgan('tiny'))
app.use(cors())
app.use(express.json())
app.use(express.static('./public'))
app.get('/:slug', async (req, res) => {
const {
slug
} = req.params
try {
const wrapper = await wrappers.findOne({
slug
})
if (wrapper) res.redirect(wrapper.url)
res.redirect(`/?error=${slug} not found.`)
} catch (error) {
res.redirect('/?error=Link not found.')
}
})
app.post('/wrappers', async (req, res, next) => {
let {
url,
slug
} = req.body
try {
if (!slug) {
slug = nanoid(6)
}
slug = slug.toLowerCase()
await schema.validate({
url,
slug
})
const newWrapper = {
url,
slug,
}
const created = await wrappers.insert(newWrapper)
res.json({
message: 'created.',
wrapper: created
})
} catch (error) {
if (error.message.startsWith('E11000')) {
error.message = 'Slug in use.'
}
next(error)
}
})
app.use((error, req, res, next) => {
if (error.status) {
res.status(error.status)
} else {
res.status(500)
}
res.json({
message: error.message,
stack: process.env.NODE_ENV === 'production' ? '🍰' : error.stack
})
});
const port = process.env.PORT || 5555
app.listen(port, () => {
console.log(`Listening at http:://0.0.0.0:${port}`)
})