Skip to content

Commit

Permalink
Make all conditions async
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Jun 18, 2022
1 parent 00a63f5 commit 8f07e03
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 5 deletions.
4 changes: 2 additions & 2 deletions docs/Routing.md
Original file line number Diff line number Diff line change
Expand Up @@ -767,7 +767,7 @@ run every time a new request arrives, and which need to return `true` for the ro
```js
// A condition that randomly allows a route to match
router.addCondition('random', (ctx, num) => {
router.addCondition('random', async (ctx, num) => {
// Winner
if (Math.floor(Math.random() * 10) === num) return true;

Expand All @@ -779,7 +779,7 @@ router.addCondition('random', (ctx, num) => {
router.get('/maybe').requires('random', 5).to('foo#bar');
```
Use whatever request information you need. Conditions can be `async` functions too.
As `async` functions, conditions can access a wide range of information.
```js
// A condition to check query parameters (useful for mock web services)
Expand Down
4 changes: 2 additions & 2 deletions src/plugins/default-conditions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export default function defaultConditionsPlugin(app: App): void {
router.addCondition('host', hostCondition);
}

function headerCondition(ctx: MojoContext, requirement: Record<string, RegExp>): boolean {
async function headerCondition(ctx: MojoContext, requirement: Record<string, RegExp>): Promise<boolean> {
for (const [name, regex] of Object.entries(requirement)) {
const value = ctx.req.get(name);
if (typeof value !== 'string') return false;
Expand All @@ -20,6 +20,6 @@ function headerCondition(ctx: MojoContext, requirement: Record<string, RegExp>):
return true;
}

function hostCondition(ctx: MojoContext, requirement: RegExp): boolean {
async function hostCondition(ctx: MojoContext, requirement: RegExp): Promise<boolean> {
return headerCondition(ctx, {Host: requirement});
}
2 changes: 1 addition & 1 deletion src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ interface RouteSpec {
websocket: boolean;
}

type RouteCondition = (ctx: MojoContext, requirements: any) => boolean;
type RouteCondition = (ctx: MojoContext, requirements: any) => Promise<boolean>;

const PLACEHOLDER = {};

Expand Down

0 comments on commit 8f07e03

Please sign in to comment.