generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 57
/
utils.ts
29 lines (25 loc) · 1.03 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { Convert, universalTypeOf } from '@web5/common';
/**
* Set/detect the media type and return the data as bytes.
*
* @beta
*/
export const dataToBlob = (data: any, dataFormat?: string) => {
let dataBlob: Blob;
// Check for Object or String, and if neither, assume bytes.
const detectedType = universalTypeOf(data);
if (dataFormat === 'text/plain' || detectedType === 'String') {
dataBlob = new Blob([data], { type: 'text/plain' });
} else if (dataFormat === 'application/json' || detectedType === 'Object') {
const dataBytes = Convert.object(data).toUint8Array();
dataBlob = new Blob([dataBytes], { type: 'application/json' });
} else if (detectedType === 'Uint8Array' || detectedType === 'ArrayBuffer') {
dataBlob = new Blob([data], { type: 'application/octet-stream' });
} else if (detectedType === 'Blob') {
dataBlob = data;
} else {
throw new Error('data type not supported.');
}
dataFormat = dataFormat || dataBlob.type || 'application/octet-stream';
return { dataBlob, dataFormat };
};