retrieve.js: separate by protocol
MODIFY
src/index.js
src/index.js
export { makeRootedResolver } from './resolve';
export { makeSuffixLocator } from './locate';
-export { makeFetchRetriever } from './retrieve';
+export { makeProtocolRetriever } from './retrieve';
export { makeImportPipeline as default } from './pipeline';

MODIFY
src/retrieve.js
src/retrieve.js
-export const DEFAULT_READFILE = path => {
- throw TypeError(`Reading files like ${path} not implemented`);
-};
-
-export const makeFetchRetriever = (fetch, readFile = DEFAULT_READFILE) => {
+export const makeProtocolRetriever = protoHandlers => {
return async moduleId => {
const url = new URL(moduleId);
- if (url.protocol === 'file:') {
- return readFile(url.pathname);
- }
- const resp = await fetch(url.href);
- if (!resp.ok) {
- throw Error(`fetching ${url.href}: ${resp.status} ${resp.statusText}`);
+ const bareProtocol = url.protocol.slice(0, -1);
+ const handler = protoHandlers[bareProtocol];
+ if (handler === undefined) {
+ throw TypeError(`Protocol retriever for ${url.protocol} not specified`);
}
- return resp.text();
+ return handler(url);
};
};

MODIFY
test/test-retrieve.js
test/test-retrieve.js
/* eslint-disable import/no-extraneous-dependencies */
import { test } from 'tape-promise/tape';
-import fetch from 'node-fetch';
import fs from 'fs';
import path from 'path';
-import { makeFetchRetriever } from '../src';
+import { makeProtocolRetriever } from '../src';
-const readFile = file => fs.promises.readFile(file, 'utf-8');
+const readFile = ({ pathname }) => fs.promises.readFile(pathname, 'utf-8');
-test.only('filesystem retriever', async t => {
+test('filesystem retriever', async t => {
try {
- const retrieve = makeFetchRetriever(fetch, readFile);
+ const retrieve = makeProtocolRetriever({ file: readFile });
const sr = `file://${path.join(__dirname, 'simple-retrieve')}`;
- console.log(sr);
+ await t.rejects(
+ retrieve('http://www.example.com'),
+ TypeError,
+ 'cannot retrieve missing protocol handler',
+ );
await t.rejects(
retrieve(`${sr}/nonexistent`),
Error,

retrieve.js: separate by protocol