Skip to content

Commit

Permalink
Support next() across multiple routes
Browse files Browse the repository at this point in the history
  • Loading branch information
frenzzy committed Oct 9, 2016
1 parent 9740ad0 commit 96e594b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 23 deletions.
36 changes: 16 additions & 20 deletions src/resolve.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,37 +24,33 @@ async function resolve(routes, pathOrContext) {
async function next() {
({ value, done } = match.next());

if (value && !done) {
if (!value || done || (result !== null && result !== undefined)) {
return result;
}

if (value.route.action) {
const newContext = Object.assign({}, context, value);

if (value.route.action) {
if (errorRoute) {
try {
return await value.route.action(newContext, newContext.params);
} catch (err) {
err.status = err.status || 500;
newContext.error = err;
return await errorRoute.action(newContext, newContext.params);
}
} else {
return await value.route.action(newContext, newContext.params);
if (errorRoute) {
try {
result = await value.route.action(newContext, newContext.params);
} catch (err) {
err.status = err.status || 500;
newContext.error = err;
result = await errorRoute.action(newContext, newContext.params);
}
} else {
result = await value.route.action(newContext, newContext.params);
}
}

return null;
return await next();
}

context.next = next;
context.end = (data) => { result = data; done = true; return data; };

while (!done) {
result = await next();

if (result !== null && result !== undefined) {
break;
}
}
result = await next();

if ((result === null || result === undefined) && errorRoute) {
context.error = new Error('Not found');
Expand Down
11 changes: 8 additions & 3 deletions test/resolve.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,17 +93,22 @@ describe('resolve(routes, { path, ...context })', () => {
const routes = [
{
path: '/test',
children: [
{ path: '/', action() { log.push(2); } },
],
async action({ next }) {
log.push(1);
await next();
log.push(3);
log.push(5);
},
},
{ path: '/test', action: () => log.push(2) },
{ path: '/:id', action() { log.push(3); } },
{ path: '/test', action() { return log.push(4); } },
{ path: '/*', action() { log.push(6); } },
];

await resolve(routes, '/test');
expect(log).to.be.deep.equal([1, 2, 3]);
expect(log).to.be.deep.equal([1, 2, 3, 4, 5]);
});

it('should support parametrized routes 1', async () => {
Expand Down

0 comments on commit 96e594b

Please sign in to comment.