Skip to content

Commit

Permalink
feat: correctly parse response bodies as JSON where the Content-Type …
Browse files Browse the repository at this point in the history
…is `application/scim+json` (#731)

GitHub has APIs that return `application/scim+json` response bodies. Currently, these responses are not parsed as JSON, and instead, an `ArrayBuffer` is returned in `response.data`.

This adds handling for `application/scim+json` so they are parsed as JSON as normal.
  • Loading branch information
timrogers authored Jan 16, 2025
1 parent 324ffef commit 00bf316
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/fetch-wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { isPlainObject } from "./is-plain-object.js";
import { RequestError } from "@octokit/request-error";
import type { EndpointInterface, OctokitResponse } from "@octokit/types";

type ContentType = ReturnType<typeof safeParse>;

export default async function fetchWrapper(
requestOptions: ReturnType<EndpointInterface>,
): Promise<OctokitResponse<any>> {
Expand Down Expand Up @@ -155,7 +157,7 @@ async function getResponseData(response: Response): Promise<any> {

const mimetype = safeParse(contentType);

if (mimetype.type === "application/json") {
if (isJSONResponse(mimetype)) {
let text = "";
try {
text = await response.text();
Expand All @@ -173,6 +175,13 @@ async function getResponseData(response: Response): Promise<any> {
}
}

function isJSONResponse(mimetype: ContentType): boolean {
return (
mimetype.type === "application/json" ||
mimetype.type === "application/scim+json"
);
}

function toErrorMessage(data: string | ArrayBuffer | Record<string, unknown>) {
if (typeof data === "string") {
return data;
Expand Down
37 changes: 37 additions & 0 deletions test/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1263,4 +1263,41 @@ x//0u+zd/R/QRUzLOw4N72/Hu+UG6MNt5iDZFCtapRaKt6OvSBwy8w==
}),
).rejects.toHaveProperty("message", "Unknown error: {}");
});

it("parses response bodies as JSON when Content-Type is application/scim+json", async () => {
expect.assertions(1);

const mock = fetchMock.createInstance();
mock.get("https://api.github.com/scim/v2/Users", {
status: 200,
body: {
totalResults: 1,
Resources: [
{
id: "123",
userName: "octocat",
},
],
},
headers: {
"Content-Type": "application/scim+json",
},
});

const response = await request("GET /scim/v2/Users", {
request: {
fetch: mock.fetchHandler,
},
});

expect(response.data).toEqual({
totalResults: 1,
Resources: [
{
id: "123",
userName: "octocat",
},
],
});
});
});

0 comments on commit 00bf316

Please sign in to comment.