Skip to content

Commit

Permalink
✨ Add support for downloading data: uris with Alchemy#download()
Browse files Browse the repository at this point in the history
skerit committed Oct 10, 2024
1 parent ecaa67b commit 6837c96
Showing 2 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -2,6 +2,7 @@

* End requests with an error when parsing posted body contents fail
* Make the max body & file size of a request configurable (per route)
* Add support for downloading `data:` uris with `Alchemy#download()`

## 1.4.0-alpha.6 (2024-09-11)

56 changes: 56 additions & 0 deletions lib/core/alchemy_functions.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
let mkdirp = alchemy.use('mkdirp')?.mkdirp,
ncp = alchemy.use('ncp').ncp,
fs = alchemy.use('fs'),
fsp = fs.promises,
libpath = alchemy.use('path'),
child = alchemy.use('child_process'),
crypto = alchemy.use('crypto'),
@@ -1106,6 +1107,53 @@ Alchemy.setMethod(function request(url, options, callback) {
return Blast.fetch(options, callback);
});

/**
* Turn a `data:` uri into a file
*
* @author Jelle De Loecker <[email protected]>
* @since 1.4.0
* @version 1.4.0
*
* @param {string} data_uri
*
* @return {Pledge<File>}
*/
function convertDataUriToFile(data_uri) {

// Split the data uri into its 2 parts
let pieces = data_uri.slice(5).split(',');

// Split the info bit
let info = pieces[0].split(';');

// Get the expected mime type
let mime_type = info[0];

// And is it base64?
let is_b64 = info[1] && info[1].toLowerCase() == 'base64';

let buffer;

if (is_b64) {
buffer = Buffer.from(pieces[1], 'base64');
} else {
buffer = Buffer.from(String.decodeURI(pieces[1]));
}

return Pledge.Swift.waterfall(
() => Blast.createTempDir({prefix: 'aldl'}),
async (temp_dir) => {
let full_path = libpath.resolve(temp_dir, 'buffer_' + alchemy.ObjectId());

await fsp.writeFile(full_path, buffer);

return full_path;
},
(full_path) => Classes.Alchemy.Inode.Inode.from(full_path)
);

}

/**
* Download a file
*
@@ -1119,6 +1167,14 @@ Alchemy.setMethod(function request(url, options, callback) {
*/
Alchemy.setMethod(function download(url, options) {

if (url.startsWith('data:')) {
try {
return convertDataUriToFile(url, options);
} catch (err) {
return Pledge.reject(err);
}
}

const pledge = new Pledge();

// Get the file

0 comments on commit 6837c96

Please sign in to comment.