UNPKG

@ou-imdt/utils

Version:

Utility library for interactive media development

37 lines (35 loc) 1.57 kB
import fetchAll from '../fetchAll.js'; import fetchAs from '../fetchAs.js'; import getUrlParam from '../getUrlParam.js'; import getFolder from './getFolder.js'; /** * Normalizes fetching VLE attachments/folders, unresolved values added to an object. * checks context for getFolder override falling back to imported if none * @param {string|object|string[]|object[]} target - Target attachment(s) to fetch. * @returns {Promise<any>} A promise that resolves with the fetched resources, or rejects on error. */ export default async function getVLEResources(target) { const list = Array.isArray(target) ? target : [target]; const unresolved = { type: 'unresolved', response: {} }; const resources = [ ...list.map(async (target) => { const { name, map } = (typeof target === 'string') ? { name: target } : target; const param = (typeof target.path === 'undefined') ? name : target.path.startsWith('?') ? target.path?.replace(/^\?/, '') : null; const path = (typeof param === 'string') ? getUrlParam(param) : target.path; try { if (/\.zip$/.test(path)) { const contents = await (this?.getFolder ?? getFolder)(param); const data = await fetchAll(contents.map(({ url }) => url), map); return data.map(data => ({ name, url: path, ...data })); } const data = await fetchAs(path) return { name, url: path, ...data }; } catch (error) { unresolved.response[name] = path; return null; } }), unresolved ]; return Promise.all(resources); }