Skip to content

Commit f4bd90a

Browse files
committed
Handle exception, refactor to simplify implementation
1 parent 32cdb8d commit f4bd90a

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

src/helpers/getJsonResponse.ts

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,17 +23,43 @@ import { IRequest } from "../typings/requestOptions";
2323
async function getJsonResponse<T>(resource: Resource, jsonRequest: T | string, requestOptions?: IRequest.Options): Promise<string>;
2424
async function getJsonResponse<T, R>(resource: Resource, jsonRequest: T | string, requestOptions?: IRequest.Options): Promise<R>;
2525

26+
/**
27+
* Makes the API call and returns the parsed JSON response.
28+
*
29+
* @template T - The type of the request payload.
30+
* @template R - The expected type of the parsed JSON response.
31+
* @param resource - The API resource responsible for handling the request.
32+
* @param jsonRequest - The request payload, either as an object or a JSON string.
33+
* @param requestOptions - Optional request options to customize the request.
34+
* @returns A promise that resolves to the parsed JSON response of type `R`, or the string "ok" for TerminalAPI responses.
35+
*/
2636
async function getJsonResponse<T, R>(
2737
resource: Resource,
2838
jsonRequest: T | string,
2939
requestOptions: IRequest.Options = {},
3040
): Promise<R | string> {
3141
const request = typeof jsonRequest === "string" ? jsonRequest : JSON.stringify(jsonRequest);
3242
const response = await resource.request(request, requestOptions);
43+
44+
if (!response) {
45+
return "" as string;
46+
}
47+
48+
if (typeof response !== "string") {
49+
return response;
50+
}
51+
52+
if (response === "ok") {
53+
// handling TerminalAPI responses
54+
return response;
55+
}
56+
3357
try {
34-
return typeof response === "string" ? JSON.parse(response) : response;
58+
return JSON.parse(response);
3559
} catch (e) {
36-
return response;
60+
console.warn("Unexpected error in getJsonResponse:", (e as Error).message);
61+
return response; // or: return response as R | string;
3762
}
3863
}
64+
3965
export default getJsonResponse;

0 commit comments

Comments
 (0)