Skip to content

Commit fe4c0aa

Browse files
authored
refactor(utils.ts): use undici's method to parse the response body into text (#221)
1 parent 67a28ee commit fe4c0aa

File tree

2 files changed

+18
-12
lines changed

2 files changed

+18
-12
lines changed

src/utils.ts

+3-9
Original file line numberDiff line numberDiff line change
@@ -41,20 +41,14 @@ export function getEncodingCharset(charset = kDefaultEncodingCharset): BufferEnc
4141
* If the response as a content type equal to 'application/json' we automatically parse it with JSON.parse().
4242
*/
4343
export async function parseUndiciResponse<T>(response: Dispatcher.ResponseData): Promise<T | string> {
44+
const body = await response.body.text();
4445
const contentTypeHeader = response.headers["content-type"] as string | undefined;
45-
const { type, parameters } = contentType.parse(
46+
const { type } = contentType.parse(
4647
contentTypeHeader ?? kDefaultMimeType
4748
);
48-
response.body.setEncoding(getEncodingCharset(parameters.charset));
49-
50-
// Reading the Node.js Stream with the AsyncIterable interface.
51-
let body = "";
52-
for await (const data of response.body) {
53-
body += data;
54-
}
5549

5650
try {
57-
return type === "application/json" ? JSON.parse(body) : body;
51+
return type === "application/json" && body ? JSON.parse(body) : body;
5852
}
5953
catch (error) {
6054
// Note: Even in case of an error we want to be able to recover the body that caused the JSON parsing error.

test/utils.spec.ts

+15-3
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,11 @@ describe("parseUndiciResponse", () => {
164164

165165
it("should parse a JSON response with no errors", async() => {
166166
const payload = JSON.stringify({ foo: "bar" });
167-
const body = stream.Readable.from(payload) as any;
167+
const body: any = {
168+
text() {
169+
return Promise.resolve(payload);
170+
}
171+
};
168172

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

182186
const payload = "{\"foo\": bar}";
183-
const body = stream.Readable.from(payload) as any;
187+
const body: any = {
188+
text() {
189+
return Promise.resolve(payload);
190+
}
191+
};
184192

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

198206
it("should parse the response as a plain/text", async() => {
199207
const payload = "hello world!";
200-
const body = stream.Readable.from(payload) as any;
208+
const body: any = {
209+
text() {
210+
return Promise.resolve(payload);
211+
}
212+
};
201213

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

0 commit comments

Comments
 (0)