Skip to content

Commit

Permalink
fix(polka): handle non-Polka multi-mount;
Browse files Browse the repository at this point in the history
- Finishes #107
  • Loading branch information
lukeed committed Oct 29, 2019
1 parent 0584bbd commit 9e4ec05
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 6 deletions.
8 changes: 3 additions & 5 deletions packages/polka/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,10 @@ class Polka extends Router {
}

use(base, ...fns) {
if (typeof base === 'function') {
super.use('/', base, fns);
} else if (base === '/') {
if (base === '/') {
super.use(base, fns.map(mount));
} else if (base instanceof Polka) {
super.use('/', [base.attach, ...fns.map(mount)]);
} else if (typeof base === 'function' || base instanceof Polka) {
super.use('/', [base, ...fns].map(mount));
} else {
super.use(base,
(req, _, next) => {
Expand Down
67 changes: 66 additions & 1 deletion packages/polka/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,71 @@ test('(polka) middleware - use(subapp)', async t => {
next();
}

const sub = (
polka()
.use(foo, bar)
.use((req, res, next) => {
t.is(req.main, true, '~> SUB ran after MAIN');
t.is(req.foo, true, '~> SUB ran after FOO');
t.is(req.bar, true, '~> SUB ran after BAR');
req.sub = true;
next();
})
.get('/item', (req, res) => {
t.pass('~> HANDLER for sub("/item") ran');
t.is(req.main, true, '~> HANDLER ran after MAIN');
t.is(req.foo, true, '~> HANDLER ran after FOO');
t.is(req.bar, true, '~> HANDLER ran after BAR');
t.is(req.sub, true, '~> HANDLER ran after SUB');
res.end('item');
})
);

// Construct the main application
const main = (
polka()
.use((req, res, next) => {
req.main = true;
next();
})
.use(sub)
);

let uri = listen(main);

console.log('GET "/item"');
// `sub` has the "/item" route
let res = await get(uri + '/item'); // +10
t.is(res.statusCode, 200, '~> received 200 status');
t.is(res.data, 'item', '~> received "item" response');

console.log('GET "/unknown"');
// 404 from `sub` application, no route
await get(uri + '/unknown').catch(err => { // +6
t.is(err.statusCode, 404, '~> received 404 status');
t.is(err.data, 'Not Found', '~> received "Not Found" response');
});

main.server.close();
});


test('(polka) middleware - use(mware, subapp)', async t => {
t.plan(21);

function foo(req, res, next) {
t.is(req.main, true, '~> FOO ran after MAIN');
req.foo = true;
next();
}

function bar(req, res, next) {
t.is(req.main, true, '~> BAR ran after MAIN');
t.is(req.foo, true, '~> BAR ran after FOO');
req.bar = true;
next();
}

const sub = (
polka()
.use(bar)
Expand Down Expand Up @@ -367,7 +432,7 @@ test('(polka) middleware - use(subapp)', async t => {
req.main = true;
next();
})
.use('/', foo, sub)
.use(foo, sub)
);

let uri = listen(main);
Expand Down

0 comments on commit 9e4ec05

Please sign in to comment.