Skip to content

Commit

Permalink
fix: base url can be nested
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Mar 16, 2022
1 parent f83c8a0 commit 28e62df
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 1 deletion.
10 changes: 9 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ const MAX_SITEMAP_LENGTH = 50 * 1000 // Max URLs in a sitemap (defined by spec)
const SITEMAP_URL_RE = /\/sitemap(-\d+)?\.xml/ // Sitemap url pattern
const SITEMAP_MAX_AGE = 24 * 60 * 60 * 1000 // Cache sitemaps for 24 hours

const TRAILING_SLASH_RE = /\/+$/

function removeTrailingSlash (str) {
return str.replace(TRAILING_SLASH_RE, '')
}

function expressSitemapXml (getUrls, base) {
if (typeof getUrls !== 'function') {
throw new Error('Argument `getUrls` must be a function')
Expand Down Expand Up @@ -139,5 +145,7 @@ function dateToString (date) {
}

function toAbsolute (url, base) {
return new URL(url, base).href
const { origin, pathname } = new URL(base)
const relative = pathname === '/' ? url : removeTrailingSlash(pathname) + url
return new URL(relative, origin).href
}
60 changes: 60 additions & 0 deletions test/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,66 @@ test('basic usage', t => {
})
})

test('nested base url', t => {
t.plan(2)

const urls = ['/sitemap-0.xml', '/sitemap-1.xml', '/sitemap-2.xml']

buildSitemaps(urls, 'https://api.teslahunt.io/cars/sitemap').then(
sitemaps => {
t.deepEqual(new Set(Object.keys(sitemaps)), new Set(['/sitemap.xml']))

t.equal(
sitemaps['/sitemap.xml'],
stripIndent`
<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://api.teslahunt.io/cars/sitemap/sitemap-0.xml</loc>
</url>
<url>
<loc>https://api.teslahunt.io/cars/sitemap/sitemap-1.xml</loc>
</url>
<url>
<loc>https://api.teslahunt.io/cars/sitemap/sitemap-2.xml</loc>
</url>
</urlset>
`
)
}
)
})

test('nested base url with trailing slash', t => {
t.plan(2)

const urls = ['/sitemap-0.xml', '/sitemap-1.xml', '/sitemap-2.xml']

buildSitemaps(urls, 'https://api.teslahunt.io/cars/sitemap/').then(
sitemaps => {
t.deepEqual(new Set(Object.keys(sitemaps)), new Set(['/sitemap.xml']))

t.equal(
sitemaps['/sitemap.xml'],
stripIndent`
<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://api.teslahunt.io/cars/sitemap/sitemap-0.xml</loc>
</url>
<url>
<loc>https://api.teslahunt.io/cars/sitemap/sitemap-1.xml</loc>
</url>
<url>
<loc>https://api.teslahunt.io/cars/sitemap/sitemap-2.xml</loc>
</url>
</urlset>
`
)
}
)
})

test('usage with all options', t => {
t.plan(2)

Expand Down

0 comments on commit 28e62df

Please sign in to comment.