Skip to content

Commit

Permalink
feat(router): allow prepare to return Response directly
Browse files Browse the repository at this point in the history
  • Loading branch information
lukeed committed Apr 2, 2021
1 parent c5d49c1 commit 50383e8
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/router.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export declare class Router {
find(method: string, pathname: string): Route|void;
run(event: FetchEvent): Promise<Response>;
onerror(req: ServerRequest, res: ServerResponse, status?: number, error?: Error): Promisable<Response>;
prepare?(req: Omit<ServerRequest, 'params'>, res: ServerResponse): Promisable<void>;
prepare?(req: Omit<ServerRequest, 'params'>, res: ServerResponse): Promisable<Response|void>;
}

// TODO?: worktop/status | worktop/errors
Expand Down
3 changes: 1 addition & 2 deletions src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,7 @@ export function Router(): RR {
let tmp, req = new ServerRequest(event);
const res = new ServerResponse(req.method);

if ($.prepare) await $.prepare(req, res);
if (res.finished) return new Response(res.body, res);
if ($.prepare && (tmp = await call($.prepare, false, req, res))) return tmp;

tmp = $.find(req.method, req.path);
if (!tmp) return call($.onerror, true, req, res, 404);
Expand Down
18 changes: 18 additions & 0 deletions types/check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,24 @@ API.add('GET', '/foo/:bar?', compose(
}
));

// Can be a Handler
API.prepare = compose(
(req, res) => {},
(req, res) => {},
(req, res) => {},
);

// Can be a Handler
API.prepare = function (req, res) {
// @ts-expect-error
req.params; // does not exist
// can now return Response instance~!
return new Response(null, { status: 204 });
}

// @ts-expect-error - numerical
API.prepare = (req, res) => 123;

/**
* WORKTOP/CACHE
*/
Expand Down

0 comments on commit 50383e8

Please sign in to comment.