Skip to content

Commit

Permalink
👩‍💻 dx: Define Blob from/to DataURL conversion utilities.
Browse files Browse the repository at this point in the history
  • Loading branch information
make-github-pseudonymous-again committed May 13, 2024
1 parent d030af1 commit c462c58
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
6 changes: 6 additions & 0 deletions imports/lib/blob/blobFromDataURL.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const blobFromDataURL = async (url: string): Promise<Blob> => {
const response = await fetch(url);
return response.blob();
};

export default blobFromDataURL;
39 changes: 39 additions & 0 deletions imports/lib/blob/blobToDataURL.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const _blobToDataURLClient = async (blob: Blob): Promise<string> =>
new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener('load', (_e) => {
resolve(reader.result as string);
});

reader.addEventListener('error', (_e) => {
reject(reader.error);
});

reader.addEventListener('abort', (_e) => {
reject(new Error('Read aborted'));
});
reader.readAsDataURL(blob);
});

const _blobToDataURLServer = async (blob: Blob): Promise<string> => {
const mimeType = blob.type;
if (mimeType === '') {
throw new Error('unknown mime-type');
}

const arrayBuffer = await blob.arrayBuffer();

const {Buffer} = await import('buffer');
const buffer = Buffer.from(arrayBuffer);

const base64 = buffer.toString('base64');

const {default: dataURL} = await import('../dataURL');
return dataURL(mimeType, base64);
};

const blobToDataURL = Meteor.isServer
? _blobToDataURLServer
: _blobToDataURLClient;

export default blobToDataURL;
26 changes: 26 additions & 0 deletions imports/lib/blob/dataURL.tests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// eslint-disable-next-line import/no-unassigned-import
import 'regenerator-runtime/runtime.js';

import {assert} from 'chai';

import {isomorphic} from '../../_test/fixtures';
import {randomPNGDataURI} from '../../_test/png';

import blobFromDataURL from './blobFromDataURL';
import blobToDataURL from './blobToDataURL';

isomorphic(__filename, () => {
it('should allow to convert back and forth from a dataURL', async () => {
if (Meteor.isServer) {
await import('../../../server/polyfill/fetch');
}

const url = randomPNGDataURI();

const blob = await blobFromDataURL(url);
assert.instanceOf(blob, Blob);

const result = await blobToDataURL(blob);
assert.equal(result, url);
});
});

0 comments on commit c462c58

Please sign in to comment.