Skip to content

Commit

Permalink
refactor(utils.ts): use undici's method to parse the response body in…
Browse files Browse the repository at this point in the history
…to text (#221)
  • Loading branch information
SofianD authored Jan 24, 2024
1 parent 67a28ee commit fe4c0aa
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
12 changes: 3 additions & 9 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,20 +41,14 @@ export function getEncodingCharset(charset = kDefaultEncodingCharset): BufferEnc
* If the response as a content type equal to 'application/json' we automatically parse it with JSON.parse().
*/
export async function parseUndiciResponse<T>(response: Dispatcher.ResponseData): Promise<T | string> {
const body = await response.body.text();
const contentTypeHeader = response.headers["content-type"] as string | undefined;
const { type, parameters } = contentType.parse(
const { type } = contentType.parse(
contentTypeHeader ?? kDefaultMimeType
);
response.body.setEncoding(getEncodingCharset(parameters.charset));

// Reading the Node.js Stream with the AsyncIterable interface.
let body = "";
for await (const data of response.body) {
body += data;
}

try {
return type === "application/json" ? JSON.parse(body) : body;
return type === "application/json" && body ? JSON.parse(body) : body;
}
catch (error) {
// Note: Even in case of an error we want to be able to recover the body that caused the JSON parsing error.
Expand Down
18 changes: 15 additions & 3 deletions test/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,11 @@ describe("parseUndiciResponse", () => {

it("should parse a JSON response with no errors", async() => {
const payload = JSON.stringify({ foo: "bar" });
const body = stream.Readable.from(payload) as any;
const body: any = {
text() {
return Promise.resolve(payload);
}
};

const data = await Utils.parseUndiciResponse<{ foo: string }>({
...defaultUndiciResponseMeta, body,
Expand All @@ -180,7 +184,11 @@ describe("parseUndiciResponse", () => {
expect.assertions(1);

const payload = "{\"foo\": bar}";
const body = stream.Readable.from(payload) as any;
const body: any = {
text() {
return Promise.resolve(payload);
}
};

try {
await Utils.parseUndiciResponse<{ foo: string }>({
Expand All @@ -197,7 +205,11 @@ describe("parseUndiciResponse", () => {

it("should parse the response as a plain/text", async() => {
const payload = "hello world!";
const body = stream.Readable.from(payload) as any;
const body: any = {
text() {
return Promise.resolve(payload);
}
};

const data = await Utils.parseUndiciResponse<string>({
...defaultUndiciResponseMeta, body, headers: {}
Expand Down

0 comments on commit fe4c0aa

Please sign in to comment.