Add option to extract server-side routes at directories other than /api.

Also clarifies some texts and documentation.
This commit is contained in:
freedmand
2018-01-05 19:21:25 -08:00
parent 7588911108
commit 9ea4137b87
2 changed files with 21 additions and 12 deletions

View File

@@ -56,13 +56,14 @@ function relativePath(url) {
/**
* Returns the Sapper API route for the specified URL path.
* @param {string} url The absolute or relative URL.
* @param {string=} apiPrefix The prefix for Sapper server-side routes.
* @return {string} The URL with /api/ in front.
*/
function apiPath(url) {
function apiPath(url, apiPrefix = '/api') {
if (url.startsWith(prefix)) {
return `${prefix}/api${url.substr(prefix.length)}`;
return `${prefix}${apiPrefix}${url.substr(prefix.length)}`;
}
return `/api${url}`;
return `${apiPrefix}${url}`;
}
/**
@@ -88,18 +89,23 @@ function getChunkFiles() {
/**
* Exports the Sapper app as a static website by starting at the root and
* crawling pages that are linked, their /api/ pages, and webpack routes, as
* well as copying assets.
* crawling pages that are linked, extracting server and client routes, and
* copying assets.
* @param {?Array<string>=} includeUrls If non-null, a set of additional URLs to
* scrape in the extraction. This should only be set if there are routes
* that cannot be reached from the root.
* @param {?Array<string>=} excludeUrls If non-null, a set of URLs to avoid
* scraping in the extraction.
* @param {string=} apiPrefix The path in which all server-side Sapper routes
* are defined. The Sapper template application uses '/api' -- if you
* diverge from the template app structure, you will want to change this. If
* your server-side Sapper routes span multiple directories, you will have
* to specify each file manually with the `includeUrls` param.
* @param {number=} extractionDir The directory in which to place the extracted
* output.
*/
module.exports = function(includeUrls = null, excludeUrls = null,
extractionDir = OUTPUT_DIR) {
apiPrefix = '/api', extractionDir = OUTPUT_DIR) {
// Set up the server.
// this allows us to do e.g. `fetch('/api/blog')` on the server
@@ -204,10 +210,11 @@ module.exports = function(includeUrls = null, excludeUrls = null,
(url) => spider.queue(getFullUrl(url), handleRequest));
}
if (relPath.endsWith('/index.html') && !relPath.startsWith('/api/')) {
// Attempt to grab the /api/ version of a page that seems to be a
// basic route.
spider.queue(apiPath(doc.url), handleRequest);
if (relPath.endsWith('/index.html') &&
!relPath.startsWith(`${apiPrefix}/`)) {
// Attempt to grab the server-side route corresponding to a page that
// seems to be a basic route.
spider.queue(apiPath(doc.url, apiPrefix), handleRequest);
}
};