Skip to content

Commit 0b943ca

Browse files
Rolando Santamaria MasoRolando Santamaria Maso
authored andcommitted
hostnames 2 prefix hook implementation
1 parent 1651942 commit 0b943ca

File tree

2 files changed

+117
-0
lines changed

2 files changed

+117
-0
lines changed

lib/hostnames-hook.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
'use strict'
2+
3+
let micromatch
4+
try {
5+
micromatch = require('micromatch')
6+
} catch (e) {
7+
micromatch = {
8+
isMatch (value, pattern) {
9+
return value === pattern
10+
}
11+
}
12+
}
13+
14+
module.exports = hostname2prefix => {
15+
const matches = {}
16+
17+
return (req, res, cb) => {
18+
if (req.headers.host) {
19+
const hostHeader = req.headers.host.split(':')[0]
20+
let prefix = matches[hostHeader]
21+
22+
if (!prefix) {
23+
for (const e of hostname2prefix) {
24+
if (micromatch.isMatch(hostHeader, e.hostname)) {
25+
prefix = e.prefix
26+
matches[hostHeader] = prefix
27+
28+
break
29+
}
30+
}
31+
}
32+
33+
if (prefix) {
34+
req.url = prefix + req.url
35+
}
36+
}
37+
38+
return cb()
39+
}
40+
}

test/hostnames-hook.test.js

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
'use strict'
2+
3+
/* global describe, it */
4+
const expect = require('chai').expect
5+
6+
describe('hostnames-hook', () => {
7+
let hostnamesHook = null
8+
9+
it('initialize', async () => {
10+
hostnamesHook = require('./../lib/hostnames-hook')([{
11+
prefix: '/nodejs',
12+
hostname: 'nodejs.org'
13+
}, {
14+
prefix: '/github',
15+
hostname: 'github.com'
16+
}, {
17+
prefix: '/users',
18+
hostname: '*.company.tld'
19+
}])
20+
})
21+
22+
it('is match - nodejs.org', (cb) => {
23+
const req = {
24+
headers: {
25+
host: 'nodejs.org:443'
26+
},
27+
url: '/about'
28+
}
29+
30+
hostnamesHook(req, null, () => {
31+
expect(req.url).to.equal('/nodejs/about')
32+
cb()
33+
})
34+
})
35+
36+
it('is match - github.com', (cb) => {
37+
const req = {
38+
headers: {
39+
host: 'github.com:443'
40+
},
41+
url: '/about'
42+
}
43+
44+
hostnamesHook(req, null, () => {
45+
expect(req.url).to.equal('/github/about')
46+
cb()
47+
})
48+
})
49+
50+
it('is match - wildcard', (cb) => {
51+
const req = {
52+
headers: {
53+
host: 'kyberneees.company.tld:443'
54+
},
55+
url: '/about'
56+
}
57+
58+
hostnamesHook(req, null, () => {
59+
expect(req.url).to.equal('/users/about')
60+
cb()
61+
})
62+
})
63+
64+
it('is not match - 404', (cb) => {
65+
const req = {
66+
headers: {
67+
host: 'facebook.com:443'
68+
},
69+
url: '/about'
70+
}
71+
72+
hostnamesHook(req, null, () => {
73+
expect(req.url).to.equal('/about')
74+
cb()
75+
})
76+
})
77+
})

0 commit comments

Comments
 (0)