Skip to content

Commit a4596cd

Browse files
committed
add initializeFunction lifecycle hook
1 parent 5c92d9b commit a4596cd

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

src/index.ts

+5-2
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import * as UserFunction from "./utils/UserFunction";
1818

1919
LogPatch.patchConsole();
2020

21-
export function run(appRoot: string, handler: string): void {
21+
export async function run(appRoot: string, handler: string): Promise<void> {
2222
if (!process.env.AWS_LAMBDA_RUNTIME_API) {
2323
throw new Error("Missing Runtime API Server configuration.");
2424
}
@@ -50,7 +50,10 @@ export function run(appRoot: string, handler: string): void {
5050
BeforeExitListener.reset();
5151
process.on("beforeExit", BeforeExitListener.invoke);
5252

53-
const handlerFunc = UserFunction.load(appRoot, handler) as HandlerFunction;
53+
const handlerFunc = (await UserFunction.load(
54+
appRoot,
55+
handler
56+
)) as HandlerFunction;
5457
const runtime = new Runtime(client, handlerFunc, errorCallbacks);
5558

5659
runtime.scheduleIteration();

src/utils/UserFunction.ts

+19-2
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,20 @@ function _loadUserApp(
110110
}
111111
}
112112

113+
async function _initializeFunction(userApp: any): Promise<void> {
114+
try {
115+
await userApp.initializeFunction();
116+
} catch (e) {
117+
if (e instanceof TypeError) {
118+
// initializeFunction lifecycle hook not implemented
119+
return;
120+
}
121+
else {
122+
throw e;
123+
}
124+
}
125+
}
126+
113127
function _throwIfInvalidHandler(fullHandlerString: string): void {
114128
if (fullHandlerString.includes(RELATIVE_PATH_SUBSTRING)) {
115129
throw new MalformedHandlerName(
@@ -137,10 +151,10 @@ function _throwIfInvalidHandler(fullHandlerString: string): void {
137151
* for traversing up the filesystem '..')
138152
* Errors for scenarios known by the runtime, will be wrapped by Runtime.* errors.
139153
*/
140-
export const load = function (
154+
export const load = async function (
141155
appRoot: string,
142156
fullHandlerString: string
143-
): HandlerFunction {
157+
): Promise<HandlerFunction> {
144158
_throwIfInvalidHandler(fullHandlerString);
145159

146160
const [moduleRoot, moduleAndHandler] = _moduleRootAndHandler(
@@ -149,6 +163,9 @@ export const load = function (
149163
const [module, handlerPath] = _splitHandlerString(moduleAndHandler);
150164

151165
const userApp = _loadUserApp(appRoot, moduleRoot, module);
166+
167+
await _initializeFunction(userApp);
168+
152169
const handlerFunc = _resolveHandler(userApp, handlerPath);
153170

154171
if (!handlerFunc) {

0 commit comments

Comments
 (0)