1

I'm using "@google-analytics/data": "^4.7.0" to request ga report, in the request array, I add some payloads which can be mocked by GA4 query explorer, payloads are like dateRanges, metrics, dimensions, metricAggregations, dimensionFilter ..., and called the function batchRunReports to get back the report.

But the error 'Cannot serialize object to proto3 JSON since its .$type is unknown. Use Type.fromObject(obj) before calling toProto3JSON.' occurs when the script run through the metricAggregations array, I don't know how come it happened and how to fix it.

The example code:

async function () {
  const { BetaAnalyticsDataClient } = require('@google-analytics/data')
  const propertyId = 'propertyId'
  const ga_auth = {
    xxx
  }

  const analyticsDataClient = new BetaAnalyticsDataClient({
    projectId: ga_auth.project_id,
    credentials: ga_auth,
    fallback: true
  })

  const requests = [
      {
        dateRanges: [{ startDate: '2024-05-30', endDate: 'today' }],
        metrics: [
          { name: 'totalUsers' },
          { name: 'screenPageViews' },
          { name: 'averageSessionDuration' },
          { name: 'screenPageViewsPerSession' },
          { name: 'bounceRate' }
        ],
        dimensions: [],
        metricAggregations: ["Total"],
        property: 'properties/propertyId',
        dimensionFilter: {
          andGroup: { expressions: [{ filter: { fieldName: 'customEvent:product_id', stringFilter: {   value: 'some_product_id' } } }] }
      }
    }
  ]

  const [response] = await analyticsDataClient.batchRunReports({
    property: `properties/${propertyId}`,
    requests
  })
  console.log(response)
  return process.exit(0)
})()

And also, I try to log out the obj passed into the toProto3Json function, I get

{ obj: Metric { name: 'totalUsers' } }
{ obj: Metric { name: 'screenPageViews' } }
{ obj: Metric { name: 'averageSessionDuration' } }
{ obj: Metric { name: 'screenPageViewsPerSession' } }
{ obj: Metric { name: 'bounceRate' } }
{ obj: DateRange { startDate: '2024-05-30', endDate: 'today' } }
{ obj: 1 }

It looks like the metricAggregations array didn't be transferred correctly, does someone know how to fix the problem? Thanks you for your reading.

I am expecting getting back correct report with totals array. When I use package "@google-analytics/data": "^3.3.0",, it got me back the correct result, but I think it's because in this version, the script didn't run the toProto3JSON function.

0