-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
95 lines (84 loc) · 2.07 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
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const mongoose = require('mongoose');
const { nanoid } = require('nanoid');
const dotenv = require('dotenv');
const app = express();
dotenv.config();
require('mongoose-type-url');
app.use(express.json());
app.use(morgan('tiny'));
app.use(cors());
app.use(express.static('client/build'));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/client/build/index.html'));
});
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
});
const Schema = mongoose.Schema;
const urlSchema = new Schema({
alias: {
type: String,
validate: {
validator: function (v) {
return /^[\w\-]*$/.test(v);
},
message: (props) => `Alias format incorrect!`,
},
unique: true,
},
url: {
type: mongoose.SchemaTypes.Url,
required: [true, 'Please enter URL!!'],
},
});
const Url = mongoose.model('Url', urlSchema);
const PORT = process.env.PORT || 1337;
app.post('/url', async (req, res, next) => {
try {
let { alias, url } = req.body;
if (!alias) {
alias = nanoid(5);
}
alias = alias.toLowerCase();
const urlObj = new Url({
url,
alias,
});
const createdEntry = await urlObj.save();
res.json(createdEntry);
} catch (err) {
console.log('here');
next(err);
}
});
app.get('/:alias', async (req, res, next) => {
const alias = req.params.alias.toLowerCase();
try {
const { url } = await Url.findOne({ alias });
console.log(url);
res.redirect(url);
} catch (err) {
next(err);
}
});
app.use((req, res, next) => {
const error = new Error('Not found');
res.status(404);
next(error);
});
app.use((error, req, res, next) => {
let statusCode = res.statusCode == 200 ? 500 : res.statusCode;
res.status(statusCode);
res.json({
stack: process.env.NODE_ENV === 'production' ? '🍰' : error.message,
});
});
app.listen(PORT, () => {
console.log(`Listening at port ${PORT}`);
});