From 51f20a48b2c120715301c70c91c6e22443f545ff Mon Sep 17 00:00:00 2001 From: Gareth Date: Tue, 20 Jun 2023 11:09:58 -0700 Subject: [PATCH] fix: module resolution returns early and accurate error messages on failure (#534) --- src/loader.ts | 25 +++++++++++++++---------- test/loader.ts | 14 ++++++++++---- 2 files changed, 25 insertions(+), 14 deletions(-) diff --git a/src/loader.ts b/src/loader.ts index 33a9525a..b1a2d6cc 100644 --- a/src/loader.ts +++ b/src/loader.ts @@ -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; } @@ -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; } diff --git a/test/loader.ts b/test/loader.ts index 1a720f6e..1fd2968b 100644 --- a/test/loader.ts +++ b/test/loader.ts @@ -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',