Skip to content

Commit

Permalink
Merge pull request #43 from MattCCC/add-media-types
Browse files Browse the repository at this point in the history
Add media types
  • Loading branch information
MattCCC authored Aug 20, 2024
2 parents 40f15f6 + fd36e8e commit 3add41b
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 7 deletions.
23 changes: 17 additions & 6 deletions src/request-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -621,25 +621,36 @@ export class RequestHandler {
(response as Response)?.headers?.get('Content-Type') || '',
);
let data;
const responseClone = response.clone();

// Handle edge case of no content type being provided... We assume json here.
if (!contentType) {
try {
data = await response.json();
data = await responseClone.json();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (_error) {
//
}
}

if (typeof data === 'undefined') {
if (contentType && contentType.includes('application/json')) {
// Parse JSON response
data = await response.json();
if (
contentType &&
(contentType.includes('application/json') ||
// This Media Type Suffix is standardizded by IETF in RFC 6839
contentType.includes('+json'))
) {
data = await response.json(); // Parse JSON response
} else if (contentType.includes('multipart/form-data')) {
data = await response.formData(); // Parse as FormData
} else if (contentType.includes('application/octet-stream')) {
data = await response.blob(); // Parse as blob
} else if (
contentType.includes('application/x-www-form-urlencoded')
) {
data = await response.formData(); // Handle URL-encoded forms
} else if (typeof response.text !== 'undefined') {
data = await response.text();
} else if (typeof response.blob !== 'undefined') {
data = await response.blob();
} else {
// Handle streams
data = response.body || response.data || null;
Expand Down
2 changes: 1 addition & 1 deletion src/types/request-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export interface BaseRequestConfig<D = any> {
export interface ExtendedResponse<T = any> extends Omit<Response, 'headers'> {
data: T;
error: ResponseError<T>;
headers: HeadersObject | HeadersInit;
headers: HeadersObject & HeadersInit;
config: ExtendedRequestConfig;
request?: ExtendedRequestConfig;
}
Expand Down
1 change: 1 addition & 0 deletions test/request-handler.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,7 @@ describe('Request Handler', () => {
}
return Promise.resolve({
ok: true,
clone: jest.fn().mockReturnValue({}),
json: jest.fn().mockResolvedValue({}),
});
});
Expand Down

0 comments on commit 3add41b

Please sign in to comment.