Skip to content

Commit

Permalink
set supported types
Browse files Browse the repository at this point in the history
  • Loading branch information
allanchau committed Mar 13, 2024
1 parent 31183b3 commit 1a26fba
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
20 changes: 16 additions & 4 deletions packages/fetch/index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
'use strict';

const parseBody = async (response) => {
const decoder = new TextDecoder();
const decoder = new TextDecoder('utf-8', { fatal: true });
let body = '';

for await (const chunk of response.body) {
body += decoder.decode(chunk);
}

if (
response.headers &&
response.headers.get('Content-Type') &&
response.headers.get('Content-Type').includes('application/json') &&
body.length
) {
Expand All @@ -21,7 +19,21 @@ const parseBody = async (response) => {
};

const parseResponse = async (response) => {
if (response.body) {
console.log('response.headers', response.headers);
console.log(
'response.headers',
/^(application\/json|text\/)/i.test(
response.headers.get('Content-Type'),
),
);
if (
response.headers &&
response.headers.get('Content-Type') &&
/^(application\/json|text\/)/i.test(
response.headers.get('Content-Type'),
) &&
response.body
) {
response.result = await parseBody(response);
}

Expand Down
28 changes: 28 additions & 0 deletions packages/fetch/tests/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -334,3 +334,31 @@ it('can handle multiple chunks', async () => {
status: 200,
});
});

it('only parses supported content-types', async () => {
expect.assertions(2);

const testPathTest = '/supported-content-types-test';
const testPathJson = '/supported-content-types-json';

app.get(testPathTest, (req, res) => {
generateResponse(req, res, {
body: { pass: true },
type: 'application/test',
});
});
app.get(testPathJson, (req, res) => {
generateResponse(req, res, {
body: { pass: true },
type: 'application/json',
});
});

await expect(
fetchApi(`${testBaseUrl}${testPathTest}`),
).resolves.not.toHaveProperty('result');

await expect(
fetchApi(`${testBaseUrl}${testPathJson}`),
).resolves.toHaveProperty('result', { pass: true });
});

0 comments on commit 1a26fba

Please sign in to comment.