2

I have several lambda functions written in Javascript. Is there any way I can wrap these handler functions to perform some common logging code?

// handlers.js
export const emailHandler = (event, context, callback) => {
   email();
}

export const loginHandler = (event, context, callback) => {
   login();
}

Something like this:

// genericHandler.js
export const genericHandler => (event, context, callback) => {
   console.log('Event', event);
   // How can I also make this work for login handler?
   return emailHandler(event, context, callback) 
}
1
  • Perhaps something like: const logEvent = fn => (event, ...args) => { console.log(event); return fn(event, ...args); } and then emailHandler = logEvent((event, context, callback) => { ... }) Commented Feb 1, 2020 at 0:49

2 Answers 2

1

I think the solution here is to is to put some common logic in a package/function that you can use in each. You don't want to include code for one Lambda function in another. As much as possible you want to reduce this size of your code so that cold starts are faster. Granted, if your code is small it won't be a big difference, but it's a bit of an anti-pattern package the same code in multiple functions, and have the code do something different based on how it's called.

With that said, you can always include multiple entry points into your function and then pass something along to decide what to call from there, or even pass the function you want to call. So something like this:

export const emailHandler = (event, context, callback) => {
   genericHandler(event, context, callback, email);
}

export const loginHandler = (event, context, callback) => {
   genericHandler(event, context, callback, login);
}

export const genericHandler => (event, context, callback, function) => {
   console.log('Event', event);
   // How can I also make this work for login handler?
   return function(event, context, callback) 
}

const email = (event, context, callback) => {
// email code
}

const login = (event, context, callback) => {
// login code
}

Sign up to request clarification or add additional context in comments.

Comments

0

You can pass a function as an argument to another function in JS. So,

// genericHandler.js
export const genericHandler => (called, event, context, callback) => {
   console.log('Event', event);
   // How can I also make this work for login handler?
   return called(event, context, callback) 
}

Then replace calls to login hander with generic handler.

genericHandler(emailHandler , event, context, callback);

A better way is to use a Proxy for each function. Check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.