Skip to content

Commit

Permalink
Merge pull request #41 from ujjwalguptaofficial/ug-feat-middleware-ex…
Browse files Browse the repository at this point in the history
…ecutor

add feature middleware execute api
  • Loading branch information
ujjwalguptaofficial authored Jan 9, 2024
2 parents 3445c40 + 582baac commit f46ad5b
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/abstracts/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,20 @@ export class Component {

private componentProp_: IComponentProp;

middleware(middleware) {
return {
execute: () => {
return new Promise<void>((res, rej) => {
middleware(this.request, this.response, (err) => {
if (err) {
rej(err)
}
else {
res();
}
});
});
}
}
}
}
41 changes: 41 additions & 0 deletions tests/general/extra/middleware.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { initServer } from "..";
import { CookieController } from "../controllers/cookie_controller";
import { viewResult, Fort, IHttpResponse } from "fortjs";

describe('DefaultController', () => {
let controller = new CookieController();

beforeAll(async () => {
await initServer();
controller.initialize();
});

it('execute middleware successfull', async () => {
let middlewareExecuted = false;
const middleware = (req, res: IHttpResponse, next) => {
middlewareExecuted = true;
next();
};

await controller.middleware(middleware).execute();
expect(middlewareExecuted).toEqual(true);
});

it('execute middleware with reject', async () => {
let middlewareExecuted = false;
const middleware = (req, res: IHttpResponse, next) => {
middlewareExecuted = true;
next("Rejected");
};
try {
await controller.middleware(middleware).execute();
} catch (error) {
expect(error).toEqual("Rejected");
}
expect(middlewareExecuted).toEqual(true);
});

afterAll(() => {
return Fort.destroy();
});
});

0 comments on commit f46ad5b

Please sign in to comment.