首页 > 解决方案 > 如何从单独的文件中导出打字稿谷歌云函数?

问题描述

结构

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

客观的

我编写了一个 Google Cloud 函数,它使用 Admin SDK 来查询我的 Firestore 数据库。这个函数写在querys.ts文件中,但需要从index.ts 这里导出,这是我现在拥有的:

index.ts

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import { query } from './Admin/querys';
export const readData = functions
  .https(query);
querys.ts

import * as admin from 'firebase-admin';
import * as fs from 'fs';

const db = admin.firestore();

export async function query() {
  const dataRef = db.collection('Collection')
  const res = await dataRef.get()
  if (res.size == 0) {
    return console.log("The query is empty")
  } else {
    res.forEach(doc => {
      const data = doc.data().consolidatedBucketId
      fs.writeFile('QueryOutput.txt', `${data} \n`, { flag: "a+" }, (err) => {
        console.log('There was an error writing to the file: ', err);
      })
      return res
    })
  }
}

调用.https(query)引发错误:

This expression is not callable.
  Type '{ onRequest: (handler: (req: Request, resp: Response<any>) => void | Promise<void>) => HttpsFunction; onCall: (handler: (data: any, context: CallableContext) => any) => TriggerAnnotated & ... 1 more ... & Runnable<...>; }' has no call signatures.

我正在尝试遵循本教程:我可以在单独的文件中编写我的云函数吗?但是,他们使用的示例不是被https调用的,我在编写所需的解决方案时遇到了麻烦。

假设:
似乎我没有async正确地从函数中返回承诺?

标签: typescriptfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


在单独的文件中编写整个函数似乎可以解决问题:

索引.ts:

import {queryFunc} from './Admin/querys'

export const query = queryFunc

查询.ts:

import * as functions from 'firebase-functions'

export const queryFunc = functions.https.onRequest((req, res) => {
  const dataRef = db.collection('Collection')
  const dataSnapshot = await dataRef.get()
  if (dataSnapshot.size == 0) {
    return console.log("The query is empty")
  } else {
    dataSnapshot.forEach(doc => {
      const data = doc.data().consolidatedBucketId
      fs.writeFile('QueryOutput.txt', `${data} \n`, { flag: "a+" }, (err) => {
        console.log('There was an error writing to the file: ', err);
      })
    })
    return res.send(dataSnapshot)
    // ^ Send the response back
  }
});

// I've renamed res (from Firestore) to dataSnapshot to avoid confusion

推荐阅读