Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve middleware extendability on implementation #5

Merged
merged 5 commits into from
Apr 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,12 @@ export abstract class Middleware {
/**
* Returns a function that have access to the request object,
* the response object, and the next middleware function.
* @param routeMetadata - A route metadata
*/
abstract getHandler(): Promise<RouteHandler>;
getRegisterCondition(): MiddlewareCondition;
abstract getHandler(routeMetadata: RouteMetadata): Promise<RouteHandler>;
getRegisterCondition(routeMethod: Methods, routeMetadata: RouteMetadata): boolean;
}

export type MiddlewareCondition = (routeMethod: Methods, routeMetadata: RouteMetadata) => boolean;

export class ControllerRegistry {
constructor(app: Express);
/**
Expand Down
4 changes: 2 additions & 2 deletions lib/controllers/ControllerRegistry.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ class ControllerRegistry {

const registerMiddleware = (middleware) => {
const canRegisterMiddleware = middleware
.getRegisterCondition()(routeMethod, routeMetadata);
.getRegisterCondition(routeMethod, routeMetadata);

if (canRegisterMiddleware) {
return middleware;
return middleware.getHandler(routeMetadata);
}
};

Expand Down
2 changes: 1 addition & 1 deletion lib/controllers/Middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class Middleware {
}
}

async getHandler() {
async getHandler(routeMetadata) {
throw new Error("Method 'getHandler()' must be implemented.");
}

Expand Down
8 changes: 3 additions & 5 deletions test/mock/MockMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Middleware, MiddlewareCondition, RouteHandler } from '../..';
import { Methods, Middleware, RouteHandler, RouteMetadata } from '../..';

export class MockMiddleware extends Middleware {

Expand All @@ -18,10 +18,8 @@ export class MockConditionalMiddleware extends Middleware {
};
}

public getRegisterCondition(): MiddlewareCondition {
return (routeMethod, routeMetadata) => {
return routeMetadata.path === '/test2';
};
public getRegisterCondition(routeMethod: Methods, routeMetadata: RouteMetadata): boolean {
return routeMetadata.path === '/test2';
}

}