morristech
3/14/2019 - 7:38 AM

Add Firebase Performance Monitoring HTTP Metrics to all Axios requests (RNFB v5). This is taken from a guide on the new React Native Firebas

Add Firebase Performance Monitoring HTTP Metrics to all Axios requests (RNFB v5). This is taken from a guide on the new React Native Firebase website (not yet ready for public use).

import axios from 'axios';
import firebase from 'react-native-firebase';

axios.interceptors.request.use(async function (config) {
  const httpMetric = firebase.perf().newHttpMetric(config.url, config.method);
  config.metadata = { httpMetric };

  // add any extra metric attributes if needed
  // await httpMetric.putAttribute('userId', '12345678');

  await httpMetric.start();
  return config;
});

axios.interceptors.response.use(async function (response) {
  const { httpMetric } = response.config.metadata;

  // add any extra metric attributes if needed
  // await httpMetric.putAttribute('userId', '12345678');

  await httpMetric.setHttpResponseCode(response.status);
  await httpMetric.setResponseContentType(response.headers['content-type']);
  await httpMetric.stop();

  return response;
}, async function (error) {
  const { httpMetric } = error.config.metadata;

  // add any extra metric attributes if needed
  // await httpMetric.putAttribute('userId', '12345678');

  await httpMetric.setHttpResponseCode(error.response.status);
  await httpMetric.setResponseContentType(error.response.headers['content-type']);
  await httpMetric.stop();

  return Promise.reject(error);
});