Skip to content

Commit

Permalink
feat(router): add compose utility;
Browse files Browse the repository at this point in the history
- TODO: Deal w/ type-inference mayhem another time.
- Related #7
  • Loading branch information
lukeed committed Apr 2, 2021
1 parent 9eee191 commit b7103b7
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
5 changes: 5 additions & 0 deletions src/router.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,8 @@ export declare class Router {

// TODO?: worktop/status | worktop/errors
export declare var STATUS_CODES: Record<string|number, string>;

/**
* Compose multiple `Handler` functions together, creating a final handler.
*/
export function compose<P extends Params = Params>(...handlers: Handler<P>[]): Handler<P>;
9 changes: 9 additions & 0 deletions src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ export function listen(handler: ResponseHandler): void {
addEventListener('fetch', reply(handler));
}

export function compose(...handlers: Handler[]): Handler {
return async function (req, res) {
for (let handler of handlers) {
let tmp = await handler(req, res);
if (tmp instanceof Response) return tmp;
if (res.finished) return new Response(res.body, res);
}
};
}
interface Entry {
keys: string[];
handler: Handler;
Expand Down
21 changes: 20 additions & 1 deletion types/check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import * as Base64 from 'worktop/base64';
import { Database, until } from 'worktop/kv';
import { ServerResponse } from 'worktop/response';
import { byteLength, HEX, uid, uuid } from 'worktop/utils';
import { listen, reply, Router, STATUS_CODES } from 'worktop';
import { listen, reply, Router, compose, STATUS_CODES } from 'worktop';

import type { KV } from 'worktop/kv';
import type { UID, UUID } from 'worktop/utils';
Expand Down Expand Up @@ -336,6 +336,25 @@ API.add('GET', /^[/]foobar[/]?/, (req) => {
assert<string>(req.params.anything);
});

/**
* WORKTOP/ROUTER
* > COMPOSE
*/

API.add('GET', '/foo/:bar?', compose(
(req, res) => {
assert<string|void>(req.params.bar);
},
async (req, res) => {
assert<string|void>(req.params.bar);
res.end('hello');
},
// @ts-expect-error
(req, res) => {
assert<string|void>(req.params.bar);
return 123;
}
));

/**
* WORKTOP/CACHE
Expand Down

0 comments on commit b7103b7

Please sign in to comment.