initial commit

This commit is contained in:
Rich Harris
2017-12-11 08:55:21 -05:00
commit e01ff8cb6b
8 changed files with 493 additions and 0 deletions

52
utils/create_matchers.js Normal file
View File

@@ -0,0 +1,52 @@
const path = require('path');
module.exports = function create_matchers(files) {
return files
.map(file => {
const parts = file.replace(/\.(html|js|mjs)$/, '').split(path.sep);
if (parts[parts.length - 1] === 'index') parts.pop();
const dynamic = parts
.filter(part => part[0] === '%')
.map(part => part.slice(1, -1));
const pattern = new RegExp(
`^\\/${parts.map(p => p[0] === '%' ? '([^/]+)' : p).join('\\/')}$`
);
const test = url => pattern.test(url);
const exec = url => {
const match = pattern.exec(url);
if (!match) return;
const params = {};
dynamic.forEach((param, i) => {
params[param] = match[i + 1];
});
return params;
};
return {
file,
test,
exec,
parts,
dynamic
};
})
.sort((a, b) => {
return (
(a.dynamic.length - b.dynamic.length) || // match static paths first
(b.parts.length - a.parts.length) // match longer paths first
);
})
.map(matcher => {
return {
file: matcher.file,
test: matcher.test,
exec: matcher.exec
}
});
}

View File

@@ -0,0 +1,39 @@
const path = require('path');
const assert = require('assert');
const create_matchers = require('./create_matchers.js');
describe('create_matchers', () => {
it('sorts routes correctly', () => {
const matchers = create_matchers(['index.html', 'about.html', '%wildcard%.html', 'post/%id%.html']);
assert.deepEqual(
matchers.map(m => m.file),
[
'about.html',
'index.html',
'post/%id%.html',
'%wildcard%.html'
]
);
});
it('generates params', () => {
const matchers = create_matchers(['index.html', 'about.html', '%wildcard%.html', 'post/%id%.html']);
let file;
let params;
for (let i = 0; i < matchers.length; i += 1) {
const matcher = matchers[i];
if (params = matcher.exec('/post/123')) {
file = matcher.file;
break;
}
}
assert.equal(file, 'post/%id%.html');
assert.deepEqual(params, {
id: '123'
});
});
});