Skip to content

Commit

Permalink
add initializeFunction lifecycle hook
Browse files Browse the repository at this point in the history
  • Loading branch information
dancfox committed Jun 3, 2021
1 parent 5c92d9b commit a4596cd
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
7 changes: 5 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import * as UserFunction from "./utils/UserFunction";

LogPatch.patchConsole();

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

const handlerFunc = UserFunction.load(appRoot, handler) as HandlerFunction;
const handlerFunc = (await UserFunction.load(
appRoot,
handler
)) as HandlerFunction;
const runtime = new Runtime(client, handlerFunc, errorCallbacks);

runtime.scheduleIteration();
Expand Down
21 changes: 19 additions & 2 deletions src/utils/UserFunction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,20 @@ function _loadUserApp(
}
}

async function _initializeFunction(userApp: any): Promise<void> {
try {
await userApp.initializeFunction();
} catch (e) {
if (e instanceof TypeError) {
// initializeFunction lifecycle hook not implemented
return;
}
else {
throw e;
}
}
}

function _throwIfInvalidHandler(fullHandlerString: string): void {
if (fullHandlerString.includes(RELATIVE_PATH_SUBSTRING)) {
throw new MalformedHandlerName(
Expand Down Expand Up @@ -137,10 +151,10 @@ function _throwIfInvalidHandler(fullHandlerString: string): void {
* for traversing up the filesystem '..')
* Errors for scenarios known by the runtime, will be wrapped by Runtime.* errors.
*/
export const load = function (
export const load = async function (
appRoot: string,
fullHandlerString: string
): HandlerFunction {
): Promise<HandlerFunction> {
_throwIfInvalidHandler(fullHandlerString);

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

const userApp = _loadUserApp(appRoot, moduleRoot, module);

await _initializeFunction(userApp);

const handlerFunc = _resolveHandler(userApp, handlerPath);

if (!handlerFunc) {
Expand Down

0 comments on commit a4596cd

Please sign in to comment.