CB-3555 :feat adds format blob to string helpers

This commit is contained in:
s.teleshev
2023-12-27 11:18:35 +01:00
parent 5041798447
commit da0ea15f17
4 changed files with 62 additions and 7 deletions
@@ -0,0 +1,23 @@
export function blobToHex(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
if (reader.result instanceof ArrayBuffer) {
const buffer = new Uint8Array(reader.result);
const hex = Array.from(buffer)
.map(byte => byte.toString(16).padStart(2, '0'))
.join('');
resolve(hex);
} else {
reject(new Error('Failed to read Blob as ArrayBuffer'));
}
};
reader.onerror = () => {
reject(new Error('Failed to read Blob'));
};
reader.readAsArrayBuffer(blob);
});
}
@@ -0,0 +1,8 @@
export function hexToBlob(hexdata: string): Blob {
const byteArray = new Uint8Array(hexdata.length / 2);
for (let x = 0; x < byteArray.length; x++) {
byteArray[x] = parseInt(hexdata.substring(x * 2, x * 2 + 2), 16);
}
return new Blob([byteArray], { type: 'application/octet-stream' });
}
+2
View File
@@ -10,6 +10,8 @@ export * from './underscore';
export * from './base64ToBlob';
export * from './blobToBase64';
export * from './blobToHex';
export * from './hexToBlob';
export * from './bytesToSize';
export * from './cacheValue';
export * from './clsx';
@@ -6,23 +6,45 @@
* you may not use this file except in compliance with the License.
*/
import { useObjectRef } from '@cloudbeaver/core-blocks';
import { blobToBase64, blobToHex } from '@cloudbeaver/core-utils';
export function useAutoFormat() {
return useObjectRef(
() => ({
format(type: string, value: string) {
if (typeof value === 'string') {
try {
switch (type) {
case 'application/json':
return JSON.stringify(JSON.parse(value), null, 2);
case 'text/xml':
case 'text/html':
return value;
case 'text/plain':
default:
return value;
}
} catch {
return value;
}
}
return value;
},
async formatBlob(type: string, value: Blob) {
try {
switch (type) {
case 'application/json':
return JSON.stringify(JSON.parse(value), null, 2);
case 'text/xml':
case 'text/html':
return value;
case 'test/base64':
return blobToBase64(value);
case 'text/hex':
return blobToHex(value);
default:
return value;
return value.text();
}
} catch {
return value;
return value.text().catch(() => {
throw new Error('Failed to read Blob');
});
}
},
}),