-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
112 lines (98 loc) · 3.06 KB
/
Copy pathserver.js
File metadata and controls
112 lines (98 loc) · 3.06 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
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
'use strict';
const Hapi = require('hapi');
const Boom = require('boom');
const Inert = require('inert');
const Dao = require('./modules/dao');
const server = Hapi.server({
port: 80,
host:'localhost'
});
const init = async () => {
await server.register(Inert);
server.route({
method: 'GET',
path: '/',
handler: {
file: {
path: 'public/index.html'
}
}
});
server.route({
method: 'GET',
path: '/app/{p*}',
handler: {
file: {
path: 'public/index.html'
}
}
});
server.route({
method: 'GET',
path: '/api/links/{token}',
handler: async (request, h) => {
let link = await Dao.findLinkByToken(encodeURIComponent(request.params.token));
return 'Requested full link: ' + JSON.stringify(link);
}
});
server.route({
method: 'GET',
path: '/api/links',
handler: async (request, h) => {
let links = await Dao.findLinks();
return JSON.stringify(links);
}
});
server.route({
method: 'POST',
path: '/api/links',
options: {
payload: {
output: 'data',
parse: true
}
},
handler: async (request, h) => {
let fullLink=request.payload.full_link;
if(fullLink) {
fullLink=fullLink.replace("https://","").replace("http://","").trim().replace(/ /g,"");
if(fullLink.length != 0){
let tokenInfo=await Dao.findTokenByFullLink(fullLink);
if(!tokenInfo) {
tokenInfo= await Dao.insert(fullLink).then((tokenInfo)=>tokenInfo);
}
return { url: tokenInfo.token, hits: tokenInfo.hits};
} else{
throw Boom.badRequest("The link cannot be empty string");
}
} else {
throw Boom.badRequest("Payload error. The full_link parameter is missing. Body must be similar to { full_link: 'www.example.com' }")
}
}
});
// used to treat clicking on the link and redirect to full link
server.route({
method: 'GET',
path: '/{token}',
handler: async (request, h) => {
let encodedToken=encodeURIComponent(request.params.token);
if(!/[^0-9a-zA-Z]/.test(encodedToken)){
let link = await Dao.findLinkByTokenAndUpdateHits(encodedToken);
if(link) {
return h.redirect('http://' + link); //302
}else{
throw Boom.notFound("SHORT LINK NOT FOUND"); //404
}
} else {
return h.file('public/'+encodedToken);
}
}
});
await server.start();
console.log(`Server running at: ${server.info.uri}`);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();