Skip to content

Commit 2620875

Browse files
committed
♻️ Improve choosing default mime type for content type request header based on body
1 parent 81bf601 commit 2620875

File tree

1 file changed

+19
-4
lines changed
  • packages/@ackee/antonio-core/src/modules/request/mimeTypes

1 file changed

+19
-4
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
import type { RequestBody } from '../../../types';
22

3-
// TODO: a possible improvement in precision of conveying document type:
4-
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#other_methods_of_conveying_document_type
53
const defaultRequestMimeTypes = {
64
string: 'application/json',
75
Blob: 'application/octet-stream',
6+
File: 'application/octet-stream',
87
ArrayBuffer: 'application/octet-stream',
98
DataView: 'application/octet-stream',
109
ReadableStream: 'application/octet-stream',
1110
URLSearchParams: 'application/x-www-form-urlencoded',
11+
FormData: 'multipart/form-data',
1212
} as const;
1313

1414
type RequestBodyType = keyof typeof defaultRequestMimeTypes;
@@ -18,7 +18,22 @@ function getBodyType(body: RequestBody): RequestBodyType {
1818
return typeof body === 'string' ? 'string' : body[Symbol.toStringTag];
1919
}
2020

21-
export function getDefaultRequestMimeType(body: RequestBody): RequestMimeType | undefined {
21+
export function getDefaultRequestMimeType(body: RequestBody): RequestMimeType | string | undefined {
2222
const bodyType = getBodyType(body);
23-
return defaultRequestMimeTypes[bodyType];
23+
const defaultMimeType = defaultRequestMimeTypes[bodyType];
24+
25+
switch (bodyType) {
26+
case 'Blob':
27+
case 'File':
28+
const blob = body as Blob;
29+
return blob.type || defaultMimeType;
30+
31+
case 'FormData':
32+
// Detect mime-type from the 1st form data value
33+
const formData = body as FormData;
34+
const firstItem = formData.values().next().value;
35+
return getDefaultRequestMimeType(firstItem);
36+
}
37+
38+
return defaultMimeType;
2439
}

0 commit comments

Comments
 (0)