You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Node.js获取当月Firestore配额、指标及读写操作用量

Node.js获取Firestore读写用量实现方案

实现思路

Firestore的读写操作用量数据默认上报到Google Cloud Monitoring服务,你可以直接调用Cloud Monitoring的API拉取指定时间范围的指标数据,再匹配官方定价规则计算月度费用即可。

前置准备

  • 安装Cloud Monitoring Node.js客户端:npm install @google-cloud/monitoring
  • 为你的Node.js服务配置GCP服务账号,为账号授予roles/monitoring.viewer权限,将服务账号密钥文件路径配置到环境变量GOOGLE_APPLICATION_CREDENTIALS中

核心代码示例

const { MetricServiceClient } = require('@google-cloud/monitoring');
const client = new MetricServiceClient();

// 配置你的GCP项目ID
const projectId = '你的GCP项目ID';
// 统计当月第一天0点到当前时间的用量
const startTime = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
const endTime = new Date();

async function getFirestoreUsage(metricType) {
  const request = {
    name: `projects/${projectId}`,
    filter: `metric.type="${metricType}" AND resource.type="firestore_database"`,
    interval: {
      startTime: {
        seconds: Math.floor(startTime.getTime() / 1000),
      },
      endTime: {
        seconds: Math.floor(endTime.getTime() / 1000),
      },
    },
    aggregation: {
      alignmentPeriod: {
        seconds: (endTime.getTime() - startTime.getTime()) / 1000,
      },
      perSeriesAligner: 'ALIGN_SUM',
    },
  };

  const [response] = await client.listTimeSeries(request);
  let total = 0;
  response.forEach(point => {
    total += point.points[0].value.int64Value;
  });
  return total;
}

// 调用获取用量并计算费用
async function calculateMonthlyCost() {
  // 读操作数
  const readCount = await getFirestoreUsage('firestore.googleapis.com/document/read_count');
  // 写操作数
  const writeCount = await getFirestoreUsage('firestore.googleapis.com/document/write_count');
  // 删除操作数
  const deleteCount = await getFirestoreUsage('firestore.googleapis.com/document/delete_count');

  console.log(`当月读操作: ${readCount}, 写操作: ${writeCount}, 删除操作: ${deleteCount}`);
  // 此处匹配Firestore对应区域的官方定价规则,扣除免费额度后乘以对应单价即可得到月度费用
}

calculateMonthlyCost().catch(console.error);

注意事项

  • 监控数据存在最多5分钟的上报延迟,月度统计场景下误差可忽略
  • 如果你的项目存在多区域部署的Firestore实例,需要在filter中补充resource.label.location="对应区域"的过滤条件,分段统计后累加
  • 业务侧自行埋点统计读写量的方案可以作为备选,但存在操作漏报的风险,优先使用官方监控数据计算费用

内容的提问来源于stack exchange,提问作者Davidsal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 02:06:03