Skip to content

Commit

Permalink
fix: module resolution returns early and accurate error messages on f…
Browse files Browse the repository at this point in the history
…ailure (#534)
  • Loading branch information
garethgeorge authored Jun 20, 2023
1 parent 41e9e8e commit 51f20a4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 14 deletions.
25 changes: 15 additions & 10 deletions src/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,11 @@ export async function getUserFunction(
try {
const functionModulePath = getFunctionModulePath(codeLocation);
if (functionModulePath === null) {
console.error('Provided code is not a loadable module.');
console.error(
`Provided code location '${codeLocation}' is not a loadable module.` +
'\nDid you specify the correct location for the module defining ' +
'your function?'
);
return null;
}

Expand Down Expand Up @@ -174,16 +178,17 @@ export async function getUserFunction(
* @return Resolved path or null.
*/
function getFunctionModulePath(codeLocation: string): string | null {
let path: string | null = null;
try {
path = require.resolve(codeLocation);
return require.resolve(codeLocation);
} catch (ex) {
try {
// TODO: Decide if we want to keep this fallback.
path = require.resolve(codeLocation + '/function.js');
} catch (ex) {
return path;
}
// Ignore exception, this means the function was not found here.
}

try {
return require.resolve(codeLocation + '/function.js');
} catch (ex) {
// Ignore exception, this means the function was not found here.
}
return path;

return null;
}
14 changes: 10 additions & 4 deletions test/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,17 @@ describe('loading function', () => {
}
}

it('fails to load a function that does not exist', async () => {
FunctionRegistry.http('function', () => {
return 'PASS';
});
it('fails to load a module that does not exist', async () => {
const loadedFunction = await loader.getUserFunction(
process.cwd() + '/test/data/does_not_exist',
'functionDoesNotExist',
'http'
);

assert.strictEqual(loadedFunction, null);
});

it('fails to load a function that does not exist', async () => {
const loadedFunction = await loader.getUserFunction(
process.cwd() + '/test/data/with_main',
'functionDoesNotExist',
Expand Down

0 comments on commit 51f20a4

Please sign in to comment.