-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontrol.js
More file actions
45 lines (39 loc) · 1.28 KB
/
control.js
File metadata and controls
45 lines (39 loc) · 1.28 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
const url = require('./model');
exports.newurl = (req, res) => {
const { longurl } = req.body;
const shorturlid = Math.random().toString(36).substring(2, 8);
const data = { longurl, shorturlid };
url.insert(data, (err) => {
if (err) {
console.error('Error inserting URL:', err);
return res.status(500).json({ error: 'Internal Server Error' });
}
res.status(201).json({
message: 'URL shortened successfully',
shorturlid
});
});
};
exports.getalls = (req, res) => {
url.getAll((err, result) => {
if (err) {
console.error('Error fetching URLs:', err);
return res.status(500).json({ error: 'Internal Server Error' });
}
res.status(200).json(result);
});
};
exports.redirectToLongUrl = (req, res) => {
const { shorturlid } = req.params;
url.getByShortUrl(shorturlid, (err, urlData) => {
if (err) {
console.error('Error fetching URL:', err);
return res.status(500).json({ error: 'Internal Server Error' });
}
if (!urlData) {
return res.status(404).json({ error: 'Short URL not found' });
}
// Redirect to the long URL
res.redirect(urlData.longurl);
});
};