Skip to content
This repository was archived by the owner on Jan 28, 2025. It is now read-only.

Commit bc2afac

Browse files
mekwalldanielcondemarin
authored andcommitted
fix: resolve relative path to custom handler (#63)
* fix: resolve relative path to custom handler * test: add missing tests for customHandlers in getFactoryHandlerCode
1 parent 55ccfe4 commit bc2afac

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

lib/__tests__/getFactoryHandlerCode.test.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,20 @@ describe("getFactoryHandlerCode", () => {
4343
);
4444
expect(compatHandlerContent).toContain("module.exports.render");
4545
});
46+
47+
it("should require custom handler", () => {
48+
const compatHandlerContent = getFactoryHandlerCode(
49+
path.join(PluginBuildDir.BUILD_DIR_NAME, "my-page.js"),
50+
"./myHandler.js"
51+
);
52+
expect(compatHandlerContent).toContain('require("./myHandler.js")');
53+
});
54+
55+
it("should require custom handler when page is nested with correct relative path", () => {
56+
const compatHandlerContent = getFactoryHandlerCode(
57+
path.join(PluginBuildDir.BUILD_DIR_NAME, "foo/bar/my-page.js"),
58+
"./myHandler.js"
59+
);
60+
expect(compatHandlerContent).toContain('require("../../myHandler.js")');
61+
});
4662
});

lib/getFactoryHandlerCode.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,21 @@ const lambdaHandlerWithFactory = `
1313
`;
1414

1515
module.exports = (jsHandlerPath, customHandlerPath) => {
16+
// convert windows path to POSIX
17+
jsHandlerPath = jsHandlerPath.replace(/\\/g, "/");
1618
const basename = path.basename(jsHandlerPath, ".js");
19+
20+
// get relative path to custom handler
21+
if (customHandlerPath) {
22+
let pathDepth = jsHandlerPath.split("/").length - 2;
23+
if (pathDepth > 0) {
24+
customHandlerPath = customHandlerPath.replace("./", "");
25+
while (pathDepth-- > 0) {
26+
customHandlerPath = `../${customHandlerPath}`;
27+
}
28+
}
29+
}
30+
1731
return lambdaHandlerWithFactory
1832
.replace(PAGE_BUNDLE_PATH, `./${basename}.original.js`)
1933
.replace(

0 commit comments

Comments
 (0)