Files
pyscript/pyscriptjs/src/plugins/calculateFetchPaths.ts
Hood Chatham 9fedfe3699 Use Promise.all to fetch files part of py-config (#1322)
This is a first step towards loading more stuff simultaneously rather
than sequentially.

The functional part of this is pretty small: call `calculateFetchPaths` and
then `Promise.all(fetchPaths.map(loadFileFromURL));`. I also transposed the
return type of `calculateFetchPaths` since it's more convenient to consume
this way.

I redid the logic in `calculateFetchPaths` a bit. I renamed `src/plugins/fetch.ts`
to `calculateFetchPaths.ts` since the file performs no fetching. I also
renamed `loadFromFile` to `loadFileFromURL`.
2023-03-29 07:32:09 -07:00

27 lines
1.2 KiB
TypeScript

import { joinPaths } from '../utils';
import { FetchConfig } from '../pyconfig';
import { UserError, ErrorCode } from '../exceptions';
export function calculateFetchPaths(fetch_cfg: FetchConfig[]): { url: string; path: string }[] {
for (const { files, to_file, from = '' } of fetch_cfg) {
if (files !== undefined && to_file !== undefined) {
throw new UserError(ErrorCode.BAD_CONFIG, `Cannot use 'to_file' and 'files' parameters together!`);
}
if (files === undefined && to_file === undefined && from.endsWith('/')) {
throw new UserError(
ErrorCode.BAD_CONFIG,
`Couldn't determine the filename from the path ${from}, please supply 'to_file' parameter.`,
);
}
}
return fetch_cfg.flatMap(function ({ from = '', to_folder = '.', to_file, files }) {
if (files !== undefined) {
return files.map(file => ({ url: joinPaths([from, file]), path: joinPaths([to_folder, file]) }));
}
const filename = to_file || from.slice(1 + from.lastIndexOf('/'));
const to_path = joinPaths([to_folder, filename]);
return [{ url: from, path: to_path }];
});
}