Skip to content

Commit

Permalink
Merge pull request #5 from joshuajaco/add-query-matcher
Browse files Browse the repository at this point in the history
Add query matcher
  • Loading branch information
joshuajaco committed Jul 28, 2023
2 parents 1c6e9d4 + fca312e commit 75b54d3
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import bodyParser from "body-parser";

export type MatcherObj = {
method?: string;
body?: string | object;
path?: string | RegExp;
query?: express.Request["query"];
headers?: Record<string, string>;
body?: string | object;
};

export type MatcherFn = (req: express.Request) => boolean;
Expand Down Expand Up @@ -184,6 +185,7 @@ function matchRequest(matcher: Matcher, req: express.Request): boolean {
return (
matchMethod(matcher, req) &&
matchPath(matcher, req) &&
matchQuery(matcher, req) &&
matchHeaders(matcher, req) &&
matchBody(matcher, req)
);
Expand All @@ -198,6 +200,16 @@ const matchPath = (matcher: MatcherObj, req: express.Request): boolean =>
? !!req.path.match(matcher.path)
: req.path === matcher.path);

const matchQuery = (matcher: MatcherObj, req: express.Request): boolean => {
if (!matcher.query) return true;

try {
return deepEqual(matcher.query, req.query, { strict: true });
} catch {
return false;
}
};

const matchHeaders = (matcher: MatcherObj, req: express.Request): boolean =>
!matcher.headers ||
Object.entries(matcher.headers).every(([k, v]) => req.headers[k] === v);
Expand Down

0 comments on commit 75b54d3

Please sign in to comment.