Skip to content

use native fetch, throw for non-2xxs #33

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## Unreleased
- Update CODEOWNERS
- Updated `getAuthorization` to use the correct API URL.
- Rename `getConnection(name: string)` -> `getAuthorization(developerName: string, attachmentNameOrColorUrl = "HEROKU_APPLINK")`, accepting a new attachmentNameOrColorOrUrl to use a specific Applink addon's config.
- Remove node-fetch in favor of native fetch, add `HTTPResponseError`

## [0.1.0-ea] - 2024-08-12

- Initial

## [1.0.0]

- Rename `getConnection(name: string)` -> `getAuthorization(developerName: string, attachmentNameOrColorUrl = "HEROKU_APPLINK")`, accepting a new attachmentNameOrColorOrUrl to use a specific Applink addon's config.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
"csv-stringify": "^6.2.3",
"jsforce": "^2.0.0-beta.24",
"luxon": "^3.2.1",
"node-fetch": "^2.7.0",
"throng": "^5.0.0",
"whatwg-mimetype": "^3.0.0"
},
Expand Down
20 changes: 14 additions & 6 deletions src/add-ons/heroku-applink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/

import { HttpRequestUtil } from "../utils/request";
import { HttpRequestUtil, HTTPResponseError } from "../utils/request";
import { OrgImpl } from "../sdk/org";
import { Org } from "../index";
import {
Expand Down Expand Up @@ -58,16 +58,24 @@ export async function getAuthorization(
try {
response = await HTTP_REQUEST.request(authUrl, opts);
} catch (err) {
if (err instanceof HTTPResponseError) {
let errorResponse;
try {
errorResponse = await err.response.json();
} catch (jsonError) {
// If JSON parsing fails, fall through to the generic error
}

if (errorResponse?.title && errorResponse?.detail) {
throw new Error(`${errorResponse.title} - ${errorResponse.detail}`);
}
}

throw new Error(
`Unable to get connection ${developerName}: ${err.message}`
);
}

// error response
if (response.title && response.detail) {
throw new Error(`${response.title} - ${response.detail}`);
}

return new OrgImpl(
response.org.user_auth.access_token,
response.org.api_version,
Expand Down
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { InvocationEventImpl } from "./sdk/invocation-event.js";
import { LoggerImpl } from "./sdk/logger.js";
import { QueryOperation } from "jsforce/lib/api/bulk";
import { getAuthorization } from "./add-ons/heroku-applink.js";
import { HTTPResponseError } from "./utils/request.js";

const CONTENT_TYPE_HEADER = "Content-Type";
const X_CLIENT_CONTEXT_HEADER = "x-client-context";
Expand Down Expand Up @@ -105,6 +106,8 @@ export function parseDataActionEvent(payload: any): DataCloudActionEvent {
return payload as DataCloudActionEvent;
}

export { HTTPResponseError };

// T Y P E S

/**
Expand Down
14 changes: 13 additions & 1 deletion src/utils/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,26 @@
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/

import fetch from "node-fetch";
/** Error thrown by the SDK when receiving non-2xx responses on HTTP requests. */
export class HTTPResponseError extends Error {
response: any;
constructor(response: Response) {
super(`HTTP Error Response: ${response.status}: ${response.statusText}`);
this.response = response;
}
}

/**
* Handles HTTP requests.
*/
export class HttpRequestUtil {
async request(url: string, opts: any, json = true) {
const response = await fetch(url, opts);

if (!response.ok) {
throw new HTTPResponseError(response);
}

return json ? response.json() : response;
}
}
30 changes: 25 additions & 5 deletions test/add-ons/heroku-applink.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import { expect } from "chai";
import sinon from "sinon";
import { HttpRequestUtil } from "../../src/utils/request";
import { HttpRequestUtil, HTTPResponseError } from "../../src/utils/request";
import { getAuthorization } from "../../src/add-ons/heroku-applink";
import { OrgImpl } from "../../src/sdk/org";

Expand Down Expand Up @@ -110,10 +110,14 @@ describe("getAuthorization", () => {
});

it("should throw error when response contains error details", async () => {
httpRequestStub.resolves({
title: "Not Found",
detail: "Authorization not found",
});
const errorResponse = new Response(
JSON.stringify({
title: "Not Found",
detail: "Authorization not found",
}),
{ status: 404 }
);
httpRequestStub.rejects(new HTTPResponseError(errorResponse));

try {
await getAuthorization("testDev");
Expand All @@ -122,4 +126,20 @@ describe("getAuthorization", () => {
expect(error.message).to.equal("Not Found - Authorization not found");
}
});

it("should handle non-JSON error responses gracefully", async () => {
const invalidJsonResponse = new Response("Invalid JSON content", {
status: 500,
});
httpRequestStub.rejects(new HTTPResponseError(invalidJsonResponse));

try {
await getAuthorization("testDev");
expect.fail("Should have thrown an error");
} catch (error) {
expect(error.message).to.equal(
"Unable to get connection testDev: HTTP Error Response: 500: "
);
}
});
});
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2648,7 +2648,7 @@ no-case@^3.0.4:
lower-case "^2.0.2"
tslib "^2.0.3"

node-fetch@^2.6.1, node-fetch@^2.7.0:
node-fetch@^2.6.1:
version "2.7.0"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.7.0.tgz#d0f0fa6e3e2dc1d27efcd8ad99d550bda94d187d"
integrity sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==
Expand Down