Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Perf: Parallelise requests #248

Merged
merged 1 commit into from
Nov 2, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 15 additions & 24 deletions lib/image.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,6 @@ function encodeSvg(content) {
);
}

async function reduceAsync(array = [], reducer = (r) => r, initial) {
for (const index of array.keys()) {
initial = await reducer(initial, array[index]); /* eslint-disable-line no-await-in-loop */
}

return initial;
}

async function assertSize(resource, maxFileSize, throwError = true) {
const {mime, contents = ''} = resource || {};
Expand Down Expand Up @@ -77,24 +70,22 @@ async function resolve(filepath, {assetPaths, maxFileSize, largeFileCallback, re
}
}

function getDataUriMapping(urls = [], options = {}) {
return reduceAsync(
[...new Set(urls)],
async (result, url) => {
const file = await resolve(url, options);
if (file && file.mime && /image/.test(file.mime)) {
result[url] = await getDataUri(file, options);
} else if (options.largeFileCallback) {
const largeFile = await resolve(url, {...options, maxFileSize: 0});
if (largeFile && largeFile.mime && /image/.test(largeFile.mime)) {
result[url] = await options.largeFileCallback(largeFile);
}
async function getDataUriMapping(urls = [], options = {}) {
const uniqueUrls = [...new Set(urls)];
const promises = uniqueUrls.map(async (url) => {
const file = await resolve(url, options);
if (file && file.mime && /image/.test(file.mime)) {
return [url, await getDataUri(file, options)];
} else if (options.largeFileCallback) {
const largeFile = await resolve(url, {...options, maxFileSize: 0});
if (largeFile && largeFile.mime && /image/.test(largeFile.mime)) {
return [url, await options.largeFileCallback(largeFile)];
}

return result;
},
{}
);
}
return [url, null];
});
const results = await Promise.all(promises);
return Object.fromEntries(results);
}

module.exports.getDataUriMapping = getDataUriMapping;
Loading