Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add media types #43

Merged
merged 3 commits into from
Aug 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading