Skip to content

Commit

Permalink
Support for cleanUrls completed
Browse files Browse the repository at this point in the history
  • Loading branch information
leo committed May 21, 2018
1 parent 6611f1d commit ed35f05
Showing 1 changed file with 69 additions and 5 deletions.
74 changes: 69 additions & 5 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,51 @@ const applicableForCleanUrl = (decodedPath, cleanUrls) => {
return matches;
};

const getPossiblePaths = (relativePath, extension) => [
path.join(relativePath, `index${extension}`),
relativePath.endsWith('/') ? relativePath.replace(/\/$/g, extension) : (relativePath + extension)
];

const findRelated = async (current, relativePath, stat, extension = '.html') => {
const possible = getPossiblePaths(relativePath, extension);

let stats = null;

for (let index = 0; index < possible.length; index++) {
const related = possible[index];
const absolutePath = path.join(current, related);

try {
stats = await stat(absolutePath);
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}

if (stats) {
return {
stats,
absolutePath
};
}
}

if (extension === '.htm') {
return null;
}

// At this point, no `.html` files have been found, so we
// need to check for the existance of `.htm` ones.
const relatedHTM = findRelated(current, relativePath, stat, '.htm');

if (relatedHTM) {
return relatedHTM;
}

return null;
};

module.exports = async (request, response, config = {}, methods = {}) => {
const cwd = process.cwd();
const current = config.public ? path.join(cwd, config.public) : cwd;
Expand All @@ -218,8 +263,8 @@ module.exports = async (request, response, config = {}, methods = {}) => {
}

const relativePath = applyRewrites(decodedPath, config.rewrites);
const absolutePath = path.join(current, relativePath);

let absolutePath = path.join(current, relativePath);
let stats = null;

try {
Expand All @@ -233,11 +278,30 @@ module.exports = async (request, response, config = {}, methods = {}) => {
}
}

if (!stats) {
response.statusCode = 404;
response.end('Not Found');
if (!stats || stats.isDirectory()) {
if (cleanUrl) {
try {
const related = await findRelated(current, relativePath, handlers.stat);

return;
if (related) {
({stats, absolutePath} = related);
}
} catch (err) {
if (err.code !== 'ENOENT') {
response.statusCode = 500;
response.end(err.message);

return;
}
}
}

if (!stats) {
response.statusCode = 404;
response.end('Not Found');

return;
}
}

const headers = await getHeaders(handlers, config.headers, relativePath, stats);
Expand Down

0 comments on commit ed35f05

Please sign in to comment.