Skip to content

Commit

Permalink
fix(transformers): parsing strings using JSON.parse threw unnecessa…
Browse files Browse the repository at this point in the history
…ry errors
  • Loading branch information
Michael committed Nov 25, 2022
1 parent 0e6eea8 commit 5774d5b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/core/transformers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { RequestExecutor, ResponseExecutor } from "../exportable-types";
import { PipelineExecutor } from "./pipelines";
import { environment } from "../environment";
import { DECODERS } from "./api/http";
import { safeJSONParse } from "../utils";

export const transformRequestData = new PipelineExecutor<RequestExecutor>((config) => {
return Promise.resolve(config);
Expand Down Expand Up @@ -58,7 +59,7 @@ export const transformResponseData = new PipelineExecutor<ResponseExecutor>((res
const bufferString = response.data.toString(responseEncoding);

if (responseType === "json") {
response.data = JSON.parse(bufferString);
response.data = safeJSONParse(bufferString, true);
} else {
response.data = bufferString;
}
Expand Down
12 changes: 12 additions & 0 deletions lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,18 @@ export function safeStringify(value: any): string {
}
}

export function safeJSONParse(value: string, returnValueOnError: boolean = false): any {
try {
return JSON.parse(value);
} catch (error) {
if (returnValueOnError) {
return value;
}

return null;
}
}

export function createEmptyScheme<T>(keys: string[]): T {
return keys.reduce((acc, key) => {
const keys = key.split(".");
Expand Down

0 comments on commit 5774d5b

Please sign in to comment.