Created
November 11, 2024 12:13
-
-
Save damianobarbati/85a25b1432782c310079b068a46dd22f to your computer and use it in GitHub Desktop.
Log decorator to log request/response
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ENV from '@api/env'; | |
import { getUserFromAsyncStorage } from '@api/helpers'; | |
import { dateToYMDHMS } from '@common/date'; | |
type LoggerParams = { | |
input?: boolean; | |
output?: boolean; | |
hideKeys?: string[]; | |
}; | |
const defaultParams: LoggerParams = { | |
input: true, | |
output: true, | |
hideKeys: [], | |
}; | |
const isPrimitive = (value) => value === Object(value); | |
export default function Log(params?: LoggerParams) { | |
const input = params?.input ?? defaultParams.input; | |
const output = params?.output ?? defaultParams.output; | |
const hideKeys = params?.hideKeys ?? defaultParams.hideKeys; | |
const replacer = (key: string, value: any) => { | |
if (isPrimitive(value)) return value; | |
else if (hideKeys?.includes('*') || hideKeys?.includes(key)) return String(value).slice(0, 5).replaceAll(/./g, '*'); | |
else return value; | |
}; | |
return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => { | |
let user_identifier: string; | |
try { | |
user_identifier = String(getUserFromAsyncStorage()?.id); | |
} catch { | |
user_identifier = 'anonymous'; | |
} | |
if (ENV.NODE_ENV === 'test') return descriptor; | |
const original = descriptor.value; | |
descriptor.value = async function (...args: any[]) { | |
let now = new Date(); | |
if (!input) console.log(`[${dateToYMDHMS(now)}][${user_identifier}] ${target.name}.${propertyKey}`); | |
else if (!hideKeys) console.log(`[${dateToYMDHMS(now)}][${user_identifier}] ${target.name}.${propertyKey} <= ${JSON.stringify(args)}`); | |
else console.log(`[${dateToYMDHMS(now)}][${user_identifier}] ${target.name}.${propertyKey} <= ${JSON.stringify(args, replacer)}`); | |
const start = Date.now(); | |
const result = await original.apply(this, args); | |
const end = Date.now(); | |
const time = end - start; | |
now = new Date(); | |
if (!output) console.log(`[${dateToYMDHMS(now)}][${user_identifier}] ${target.name}.${propertyKey} in ${time}ms`); | |
else if (!hideKeys) console.log(`[${dateToYMDHMS(now)}][${user_identifier}] ${target.name}.${propertyKey} in ${time}ms => ${JSON.stringify(result)}`); | |
else console.log(`[${dateToYMDHMS(now)}][${user_identifier}] ${target.name}.${propertyKey} in ${time}ms => ${JSON.stringify(result, replacer)}`); | |
return result; | |
}; | |
return descriptor; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment