You need to enable JavaScript to run this app. 如何从单独文件导出TypeScript编写的Google Cloud Function?
优惠活动
大模型
产品
解决方案
定价
更多

如何从单独文件导出TypeScript编写的Google Cloud Function?

项目结构

functions
|--src
    |--index.ts
    |--Admin
        |--querys.ts
        |--migrations.ts

报错原因

  • Firebase HTTPS云函数触发方法语法错误:functions.https本身不是可调用函数,需要明确指定触发类型:onRequest(适配普通HTTP请求)或onCall(适配客户端SDK调用的可调用云函数)
  • 当前定义的query函数不符合HTTPS处理函数的参数要求,onRequest类型的处理函数必须接收请求对象req和响应对象res两个入参
  • 隐含问题1:云函数运行环境仅允许写入/tmp临时目录,直接写入当前目录的QueryOutput.txt会触发权限报错;且回调式的fs.writeFile不会等待执行完成,函数可能在写文件操作结束前就被销毁
  • 隐含问题2:未初始化Firebase Admin SDK,后续调用Admin接口会直接报错

修复代码

1. 修复index.ts

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import { query } from './Admin/querys';

// 初始化Admin SDK,必填
admin.initializeApp();

export const readData = functions
  .https.onRequest(query); // 明确指定使用onRequest触发

2. 修复querys.ts

import * as admin from 'firebase-admin';
import * as fs from 'fs/promises'; // 改用Promise版本的fs接口方便异步等待
import type { Request, Response } from 'firebase-functions/v1/https';

const db = admin.firestore();

export async function query(req: Request, res: Response) {
  try {
    const dataRef = db.collection('Collection')
    const snapshot = await dataRef.get()
    if (snapshot.empty) {
      return res.status(200).send("The query is empty");
    }
    // 先批量收集所有数据,避免循环IO损耗
    const resultList: string[] = [];
    snapshot.forEach(doc => {
      const id = doc.data().consolidatedBucketId
      if (id) resultList.push(id);
    })
    // 写入云函数允许的临时目录
    await fs.writeFile('/tmp/QueryOutput.txt', resultList.join('\n'), { flag: "a+" });
    // 返回结果给调用方
    return res.status(200).json({
      count: resultList.length,
      data: resultList
    });
  } catch (err) {
    console.error('执行出错:', err);
    return res.status(500).send('Server Error');
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 22:48:00