Skip to content

Commit

Permalink
fix: decoding when charset is in the content type response header (#904)
Browse files Browse the repository at this point in the history
  • Loading branch information
manchuck authored Jan 22, 2024
1 parent 05cbf33 commit aec47d6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
6 changes: 5 additions & 1 deletion packages/numbers/__tests__/__dataSets__/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ export default [
request: {
url: BASE_URL,
intercept: [`/number/search?api_key=12345&api_secret=ABCDE`, 'GET'],
reply: [200, validResponse],
reply: [
200,
validResponse,
{ 'Content-Type': 'application/json;charset=utf-8' },
],
},
parameters: [{}],
expected: validResponse,
Expand Down
19 changes: 16 additions & 3 deletions packages/server-client/lib/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,6 @@ export class Client {
response: Response,
): Promise<VetchResponse<T>> {
let decoded = null;

if (!response.ok) {
log('Request failed', response);
throw new VetchError(
Expand All @@ -369,33 +368,47 @@ export class Client {
response,
);
}
log('Request succeeded');

// eslint-disable-next-line max-len
const [contentType] = (response.headers.get('content-type') || '').split(
';',
);
log(`Response content type: ${contentType}`);

switch (response.headers.get('content-type')) {
switch (contentType) {
case ContentType.FORM_URLENCODED:
log('Decoding form data');
decoded = response.body
? new URLSearchParams(await response.text())
: '';
break;
case ContentType.JSON:
log('Decoding JSON');
decoded = await response.json();
break;
default:
log('Decoding text');
decoded = await response.text();
}

log('Decoded body', decoded);
const responseHeaders = {};

for (const [header, value] of response.headers.entries()) {
Object.assign(response, header, value);
}

return {
const result = {
data: decoded as T,
config: request,
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
request: request,
} as VetchResponse<T>;

log('Response', JSON.stringify(result, null, 2));
return result;
}
}

0 comments on commit aec47d6

Please sign in to comment.