import * as middy from "middy";

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

interface ICommonMiddlewareOptions {
  error?: Error;
}

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 }) => {
      if (options.error) {
        throw options.error;
      } else {
        throw error;
      }
    },
  } as middy.IMiddyMiddlewareObject;
};
