import * as middy from "middy";

export function initCommonMiddlewares(handler): middy.IMiddy {
  return middy(handler).use(commonMiddleware({}));
}

interface ICommonMiddlewareOptions {}

export const commonMiddleware = (options: ICommonMiddlewareOptions) => {
  return {
    before: async (handler) => {
      const { identity } = handler.context;
      const { event } = handler;
      console.log("Run handler", JSON.stringify({ identity, event }));
    },
    after: async (handler) => {
      const { response } = handler;
      console.log("Finalize handler", JSON.stringify({ response }));
    },
    onError: async ({ error }) => {
      throw error;
    },
  } as middy.IMiddyMiddlewareObject;
};
