-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
99 lines (81 loc) · 2.23 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
95
96
97
98
99
import express from 'express'
import cors from 'cors'
import morgan from 'morgan'
import helmet from 'helmet'
import yup from 'yup'
import { nanoid } from 'nanoid'
import dotenv from 'dotenv'
import mongoose from 'mongoose';
import UrlDb from './db.js';
import path from 'path';
import { dirname } from 'path';
import { fileURLToPath } from 'url';
dotenv.config()
mongoose.connect(process.env.MONGO_URI)
const app = express()
const PORT = process.env.PORT || 4500;
app.use(helmet())
app.use(morgan('tiny'))
app.use(cors())
app.use(express.json())
app.use(express.static('./public'))
// Get __dirname equivalent
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Use path.join
const notFoundPath = path.join(__dirname, 'public/404.html');
app.get('/', (req, res)=>{
res.json({
meessage: 'short urls just for you'
})
})
app.get('/:id', async (req, res, next) => {
const { id: slug } = req.params;
try {
const url = await UrlDb.findOne({ slug });
if (url) {
return res.redirect(url.url);
}
return res.status(404).sendFile(notFoundPath)
} catch (e) {
return res.status(404).sendFile(notFoundPath)
}
});
app.post('/url', async (req, res, next)=>{
//create a short url
var { slug, url } = req.body;
try{
await schema.validate({
slug,
url
})
if(!slug){
slug = nanoid(5);
}else{
const existing = await UrlDb.findOne({ slug })
if(existing){
return res.status(400).json({ message: 'Slug already in use. 🍕' });
}
}
slug = slug.toLowerCase();
const newUrl = new UrlDb({
url,
slug,
new_url: `https://hp-us.vercel.app/${slug}`
})
const created = await newUrl.save()
res.status(200).json(created)
}catch(e){
next(e)
}
})
const schema = yup.object().shape({
slug: yup.string().trim().matches(/[\w\-]/i),
url: yup.string().trim().url(),
})
app.use((req, res, next) => {
res.status(404).sendFile(notFoundPath);
});
app.listen(PORT, ()=>{
console.log(`Listening on port ${PORT}`);
})