
import logger from '../utils/logger'

export const isTargetRequest = (ctx, whiteList) => {
  const method = ctx.request.method.toUpperCase()
  const { url } = ctx.request
  const checked = whiteList.some(option => option.method === method && option.url.test(url))
  if (checked) logger.info(`[WHITELIST][method:${method}] ${url}`)
  return checked
}

const loggerMiddleware = (options = {}) => async (ctx, next) => {
  const { whiteList = [] } = options
  const checkWhite = await isTargetRequest(ctx, whiteList)
  if (checkWhite) return await next()

  const url = ctx.request.URL
  const { pathname } = url
  const {
    device,
    browser,
    platform
  } = ctx.state

  logger.info(
    [
      `[path] ${pathname}`,
      `[method] ${ctx.request.method}`,
      `[${device}] ${browser}:${platform}`,
      `[query] ${JSON.stringify(ctx.query)}`,
      `[body] ${JSON.stringify(ctx.request.body)}`,
      `[session] ${JSON.stringify(ctx.session)}`
    ].join('\n')
  )
  await next()
}

export default loggerMiddleware

@@ -697,20 +697,20 @@
       %60%5B
-path
+PATH
 %5D $%7Bpath
@@ -725,22 +725,22 @@
       %60%5B
-method
+METHOD
 %5D $%7Bctx.
@@ -769,16 +769,62 @@
   %60%5B
-$%7Bdevice
+IP%5D $%7Bctx.request.ip%7D%60,%0A      %60%5B$%7Bdevice.toUpperCase()
 %7D%5D $
@@ -855,21 +855,21 @@
       %60%5B
-query
+QUERY
 %5D $%7BJSON
@@ -901,20 +901,20 @@
       %60%5B
-body
+BODY
 %5D $%7BJSON
@@ -953,23 +953,23 @@
       %60%5B
-session
+SESSION
 %5D $%7BJSON

change logger