Skip to content

Commit

Permalink
fix: handler execute cycle bug fix
Browse files Browse the repository at this point in the history
  • Loading branch information
aaydin-tr committed Dec 26, 2023
1 parent e7c269a commit 8289d43
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 37 deletions.
40 changes: 4 additions & 36 deletions src/context.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Server } from "bun";
import { Handler, Handlers } from "./types";
import { HttpMethod } from "./utils";
import { parse } from "fast-querystring";
import { Routes } from "./route";

export class Context {
private _queries: Record<string, string> | null = null;
Expand Down Expand Up @@ -36,9 +36,8 @@ export class Context {
* Calls the next handler in the chain.
*
*/
public next(): Context {
this.routes!.next(this);
return this;
public next(): void | Context | Promise<void | Context> {
return this.routes!.next(this);
}

/**
Expand Down Expand Up @@ -202,7 +201,7 @@ export class Context {
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public async body(): Promise<any | FormData | string | ArrayBuffer> {
public async body(): Promise<FormData | string | ArrayBuffer | null> {
if (this.method === HttpMethod.GET || this.method === HttpMethod.HEAD)
return null;
if (this.req.bodyUsed) return this._body;
Expand Down Expand Up @@ -554,34 +553,3 @@ class Local {
this.locals.clear();
}
}

type RouteHandler = {
handler: Handler;
done: boolean;
};

export class Routes {
private routes: RouteHandler[] = [];
constructor(handlers: Handlers) {
this.routes = handlers.map((handler) => ({
handler: handler,
// TODO find a better way to do this
done: false,
}));
}

public async start(ctx: Context): Promise<void> {
if (this.routes.length === 0) return;
const handler = this.routes[0];
handler.done = true;
await handler.handler(ctx);
}

public async next(ctx: Context): Promise<void> {
// TODO: performance check
const nextHandler = this.routes.find((handler) => !handler.done);
if (!nextHandler) return;
nextHandler.done = true;
await nextHandler.handler(ctx);
}
}
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export interface Group {

export type Handler = (
ctx: Context
) => Context | Promise<Context> | void | Promise<void>;
) => Promise<void | Context> | void | Context;

export type Handlers = Handler[];

Expand Down

0 comments on commit 8289d43

Please sign in to comment.