Skip to content

fix: module resolution returns early and accurate error messages on failure #534

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

Merged
merged 3 commits into from
Jun 20, 2023
Merged
Show file tree
Hide file tree
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
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