Skip to content

Commit

Permalink
Merge pull request #797 from pmcelhaney/server-dispatcher-handle-requ…
Browse files Browse the repository at this point in the history
…ests-with-basepath

feat(server): Add dispatcher logic to allow handling requests container OpenApi basePath
  • Loading branch information
pmcelhaney committed Mar 13, 2024
2 parents 9315009 + ee50592 commit ca5fde0
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/sweet-nails-itch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"counterfact": patch
---

Allows Counterfact to handle requests that contain the OpenApi basePath
12 changes: 11 additions & 1 deletion src/server/dispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ interface ParameterTypes {
}

export interface OpenApiDocument {
basePath?: string;
paths: {
[key: string]: {
[key in Lowercase<HttpMethods>]?: OpenApiOperation;
Expand Down Expand Up @@ -203,7 +204,7 @@ export class Dispatcher {
return false;
}

// eslint-disable-next-line sonarjs/cognitive-complexity
// eslint-disable-next-line sonarjs/cognitive-complexity, max-statements
public async request({
body,
headers = {},
Expand All @@ -227,6 +228,15 @@ export class Dispatcher {
}): Promise<NormalizedCounterfactResponseObject> {
debug(`request: ${method} ${path}`);

// If the incoming path includes the base path, remove it
if (
this.openApiDocument?.basePath !== undefined &&
path.toLowerCase().startsWith(this.openApiDocument.basePath.toLowerCase())
) {
// eslint-disable-next-line security/detect-non-literal-regexp
path = path.replace(new RegExp(this.openApiDocument.basePath, "iu"), "");
}

const { matchedPath } = this.registry.handler(path);
const operation = this.operationForPathAndMethod(matchedPath, method);

Expand Down
50 changes: 50 additions & 0 deletions test/server/dispatcher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -769,3 +769,53 @@ describe("given an invalid path", () => {
);
});
});

describe("given a request that contains the OpenApi basePath", () => {
it("strips the basePath from the path before finding the associated handler", async () => {
const registry = new Registry();

registry.add("/abc", {
POST() {
return {
body: "ok",
status: 200,
};
},
});

const dispatcher = new Dispatcher(registry, new ContextRegistry(), {
basePath: "/api",

paths: {
"/abc": {
post: {
responses: {
200: {
content: {
"text/plain": {
schema: {
type: "string",
},
},
},
},
},
},
},
},
});

const response = await dispatcher.request({
body: "",
headers: {},
method: "POST",
path: "/api/abc",
query: {},
req: { path: "/api/abc" },
});

expect(response.status).toBe(200);

expect(response.body).toBe("ok");
});
});

0 comments on commit ca5fde0

Please sign in to comment.