-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
80 lines (61 loc) · 1.66 KB
/
server.js
File metadata and controls
80 lines (61 loc) · 1.66 KB
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
const express = require('express');
const mongo = require('mongodb');
const monk = require('monk');
const yup = require('yup');
const app = express();
const dotenv = require('dotenv').config();
const PORT = process.env.PORT || 5000;
let db = monk(process.env.MONGO_URI);
const urls = db.get('urls');
urls.createIndex('name');
const schema = yup.object().shape({
id: yup.string().trim().required(),
url: yup.string().trim().url().required()
});
app.use(express.static('./static'));
app.use(express.json());
app.use((error, req, res, next) => {
});
app.post('/shorten', async (req, res) => {
let {id, url} = req.body;
try{
await schema.validate({
id, url
});
const exists = await urls.findOne({id});
if(exists){
res.status(500);
res.json({error: "ID is in use"});
}else{
const newUrl = {
id, url
};
const created = await urls.insert(newUrl);
res.status(200);
res.json(created);
}
}catch (error){
res.json({
message: error.message,
stack: error.stack
});
}
});
app.get('/:id', async (req, res) =>{
let id = req.params.id;
try{
const entry = await urls.findOne({id});
if(entry){
res.redirect(entry.url);
}else{
res.redirect('/');
}
}catch{
}
});
app.get('/', (req, res) => {
res.sendFile('./static/index.html');
});
app.listen(PORT, () =>{
console.log(`Server Listening on port ${PORT}`);
});