-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
170 lines (97 loc) · 3.37 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
const express = require('express')
const morgan = require('morgan')
const yup = require('yup')
const helmet = require('helmet')
const cors = require('cors')
const monk = require('monk')
const util = require('util')
const path = require("path");
var bodyParser = require('body-parser');
const { nanoid } = require("nanoid");
var validUrl = require("valid-url");
const { MongoError } = require('mongodb')
if(process.env.NODE_ENV!=="production") require("dotenv").config();
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
const db = monk(process.env.MONGODB_URI);
//
db.on("open", () => {
console.log("Database connected.");
});
db.addMiddleware(require('monk-middleware-debug'))
const urls = db.get("urls");
urls.createIndex({ slug: 1 }, { unique: true });
console.log("objects"+util.inspect(urls, {showHidden: false, depth: null}))
app.use(helmet())
//logger with tiny message
app.use(morgan('tiny'))
//app.use(cors())
app.use(express.json())
//define te static folder for the server side
app.use(express.static('./public'));
const errorPage = path.join(__dirname, "public/404.html");
///cors policy managment middleware
//CORS Should be restricted
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
next();
});
app.post('/url', async (req,res,next)=>{
let { slug, url } = req.body;
if (!url) {
return res.status(400).send({ error: "url is required" });
}
// Check if the image_url is a valid url.
if (!validUrl.isUri(url)) {
return res.status(400).send({ error: "url must be a valid url" });
}
if (!slug) {
// generate a random slug
slug = nanoid(5);
slug = slug.toLowerCase();
}else{
//check if the slug exist in the database
const existing = await urls.findOne({ slug });
if (existing) {
return res.status(404).send({ error: `Slug ${slug} in use. 🍔` });
}
}
const created = urls.insert({ slug: slug, url: url }).then(docs => {
// send feed back
res.json(docs);
})
.catch(err => {
return res.status(404).send({ error: err });
next(error);
});
})
app.get('/:slug',async (req,res)=>{
const { slug } = req.params;
const existing = await urls.findOne({ slug });
if (existing) {
res.redirect(existing.url);
} else {
res.status(404).sendFile(errorPage);
}
});
//error is e=sent from the app.get above
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 || 1337;
//configurin server listening
app.listen(port,()=>{
console.log(`Listening at http://localhost:${port}`);
});