-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathurl.controller.js
More file actions
68 lines (61 loc) · 2.15 KB
/
url.controller.js
File metadata and controls
68 lines (61 loc) · 2.15 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
//import Url model
const Url = require('./url.model.js');
//This is basically your domain name
const baseUrl = process.env.BASE_URL || 'http://localhost:'+process.env.PORT;
const createShortLink = async (req, res) => {
//get the originalUrl and unique_name from the request's body
let { originalUrl, unique_name } = req.body;
try {
//check if unique_name alredy exists
let nameExists = await Url.findOne({ unique_name });
/** if unique_name already exists, send a response with an
error message, else save the new unique_name and originalUrl */
if(nameExists){
return res.status(403).json({
error: "Unique name already exists, choose another",
ok : false
})
}
else {
const shortUrl = baseUrl + '/' + unique_name;
url = new Url({
originalUrl,
shortUrl,
unique_name
});
//save
const saved = await url.save();
//return success message shortUrl
return res.json({
message : 'success',
ok : true,
shortUrl
});
}
} catch (error) {
///catch any error, and return server error
return res.status(500).json({ok : false, error : 'Server error'});
}
};
const openShortLink = async (req, res) => {
//get the unique name from the req params (e.g olamide from shorten.me/olamide)
const { unique_name } = req.params;
try{
//find the Url model that has that unique_name
let url = await Url.findOne({ unique_name });
/** if such Url exists, redirect the user to the originalUrl
of that Url Model, else send a 404 Not Found Response */
if(url){
return res.redirect(url.originalUrl);
} else {
return res.status(404).json({error : 'Not found'});
}
} catch(err) {
//catch any error, and return server error to user
console.log(err);
res.status(500).json({error : 'Server error'});
}
};
module.exports = {
createShortLink, openShortLink
}