import {convertToError, isPromise} from '../utils/instrumentation-helpers'; import InstrumentationModule from '../../native/InstrumentationModule'; function sanitizeCustomData(object: any): any { switch (typeof object) { case 'symbol': { return object.description; } case 'function': { // Remove function body const split = object.toString().split('{'); const [functionName] = split; return functionName.slice(0, -1); } default: { return `${object}`; } } } /** * Helps tracking functions and their implementation. * * The {@link InfoPoint} decorator provides an easier way to add info points to your app. * Consider using that as a first resort. * * ```tsx * async function downloadImage(url) { * return Instrumentation.trackCall('DownloadService', 'downloadImage', [url], async () => { * const request = createRequest(url); * const response = await request.execute(); * if (response.status >= 400) { * throw new Error(`Bad status code: ${response.status}`); * } * return response.data; * }); * ``` * * @param {string} className Name of the class where the function is called. * @param {string} functionName Name of the class where the function is called. * @param {any[]} args Function's arguments. * @param {Function} executionCallback Function's implementation/body. */ async function trackCall( className: string, functionName: string, args: any[], executionCallback: () => T | Promise, ): Promise { const id = await InstrumentationModule.beginCall( className, functionName, args.map(element => sanitizeCustomData(element)), false, ); try { const ret = executionCallback(); if (isPromise(ret)) { return ret.then(onSuccess, onFailure); } return onSuccess(ret); } catch (error) { return onFailure(error); } async function onSuccess(result: T): Promise { await InstrumentationModule.endCallWithSuccess(id, { result: sanitizeCustomData(result), }); return result; } async function onFailure(error: any): Promise { await InstrumentationModule.endCallWithError(id, convertToError(error)); throw error; } } export default trackCall;