Skip to content

Commit 50980b7

Browse files
committed
fix(api-server): lambdaLoader: improve handler import logic...
For ESModule and CommonJS compatibility. When using a bundler like Rollup, the handler function is exported as default.
1 parent 427e92a commit 50980b7

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

packages/api-server/src/plugins/lambdaLoader.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,26 @@ export const setLambdaFunctions = async (foundFunctions: string[]) => {
2828
const ts = Date.now()
2929
const routeName = path.basename(fnPath).replace('.js', '')
3030

31-
const { handler } = await import(`file://${fnPath}`)
31+
const fnImport = await import(`file://${fnPath}`)
32+
const handler: Handler = (() => {
33+
if ('handler' in fnImport) {
34+
// ESModule export of handler - when using `export const handler = ...` - most common case
35+
return fnImport.handler
36+
}
37+
if ('default' in fnImport) {
38+
if ('handler' in fnImport.default) {
39+
// CommonJS export of handler - when using `module.exports.handler = ...` or `export default { handler: ... }`
40+
// This is less common, but required for bundling tools that export a default object, like esbuild or rollup
41+
return fnImport.default.handler
42+
}
43+
// ESModule export of default function - fallback
44+
return fnImport.default
45+
}
46+
throw new Error(
47+
`Function "${routeName}" at "${fnPath}" does not export a "handler" function.`,
48+
)
49+
})()
50+
3251
LAMBDA_FUNCTIONS[routeName] = handler
3352
if (!handler) {
3453
console.warn(

0 commit comments

Comments
 (0)