Skip to content

Commit 51ee61e

Browse files
RubenVerborghrubensworks
authored andcommitted
Support Express request objects in ResourceMapper.
1 parent 9dac622 commit 51ee61e

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

lib/resource-mapper.js

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,14 +81,29 @@ class ResourceMapper {
8181

8282
// Determine the full file path corresponding to a URL
8383
_getFullPath (url) {
84-
const { pathname, hostname } = typeof url === 'string' ? URL.parse(url) : url
84+
const { pathname, hostname } = this._parseUrl(url)
8585
const fullPath = decodeURIComponent(`${this.getBasePath(hostname)}${pathname}`)
8686
if (fullPath.indexOf('/..') >= 0) {
8787
throw new Error('Disallowed /.. segment in URL')
8888
}
8989
return fullPath
9090
}
9191

92+
// Parses a URL into a hostname and pathname
93+
_parseUrl (url) {
94+
// URL specified as string
95+
if (typeof url === 'string') {
96+
return URL.parse(url)
97+
}
98+
// URL specified as Express request object
99+
if (!url.pathname && url.path) {
100+
const { hostname, path } = url
101+
return { hostname, pathname: path.replace(/[?#].*/, '') }
102+
}
103+
// URL specified as object
104+
return url
105+
}
106+
92107
// Gets the expected content type based on the extension of the path
93108
_getContentTypeByExtension (path) {
94109
const extension = /\.([^/.]+)$/.exec(path)

test/unit/resource-mapper-test.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,34 @@ describe('ResourceMapper', () => {
306306
contentType: 'text/html'
307307
})
308308

309+
itMapsUrl(mapper, 'a URL with a host specified as a URL object',
310+
{
311+
url: {
312+
hostname: 'example.org',
313+
path: '/space/foo.html'
314+
},
315+
contentType: 'text/html',
316+
createIfNotExists: true
317+
},
318+
{
319+
path: `${rootPath}example.org/space/foo.html`,
320+
contentType: 'text/html'
321+
})
322+
323+
itMapsUrl(mapper, 'a URL with a host specified as an Express request object',
324+
{
325+
url: {
326+
hostname: 'example.org',
327+
pathname: '/space/foo.html'
328+
},
329+
contentType: 'text/html',
330+
createIfNotExists: true
331+
},
332+
{
333+
path: `${rootPath}example.org/space/foo.html`,
334+
contentType: 'text/html'
335+
})
336+
309337
itMapsUrl(mapper, 'a URL with a host with a port',
310338
{
311339
url: 'http://example.org:3000/space/foo.html',

0 commit comments

Comments
 (0)