-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
93 lines (82 loc) · 2.17 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
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const helmet = require('helmet');
const yup = require('yup');
const monk = require('monk');
const { nanoid } = require('nanoid');
require('dotenv').config();
const db = monk(process.env.MONGODB_URI);
const urls = db.get('urls');
urls.createIndex({ slug: 1 }, { unique: true });
const app = express();
app.use(helmet());
app.use(morgan('tiny'));
app.use(cors());
app.use(express.json());
app.use(express.static('./public'));
app.get('/', (req, res) => {
res.json({
message: 'sta.radio - Short URLs for STAR'
});
});
app.get('/url/:id', (req, res) => {
// get a short URL by ID
});
app.get('/:id', async (req, res) => {
const { id: slug } = req.params;
try {
const url = await urls.findOne({ slug });
if (url) {
res.redirect(url.url);
}
res.redirect(`/?error=${slug} not found`);
} catch (error) {
res.redirect(`/?error=Link not found`);
}
});
const schema = yup.object().shape({
slug: yup.string().trim().matches(/[\w\-]/i),
url: yup.string().trim().url().required(),
})
app.post('/url', async (req, res, next) => {
let { slug, url} = req.body;
try {
await schema.validate({
slug,
url,
});
if (!slug) {
slug = nanoid(5);
} else {
const existing = await urls.findOne({ slug });
if (existing) {
throw new Error('Slug already in use.');
}
}
slug = slug.toLowerCase();
const newUrl = {
url,
slug,
};
const created = await urls.insert(newUrl);
res.json(created);
} catch (error) {
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' ? 'success' : error.stack,
});
})
const port = process.env.PORT || 1337;
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}`);
});