typescript - 如何从单独的文件中导出打字稿谷歌云函数?
问题描述
结构
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
正确地从函数中返回承诺?
解决方案
在单独的文件中编写整个函数似乎可以解决问题:
索引.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
推荐阅读
- excel - 是否可以使用 Spreadsheetgear - C# .NET 将表格添加到 excel(excel 方式是 INSERT->Table)
- css - 平滑的 CSS 动画向上滚动?
- java - java 1.6中的字符串操作
- javascript - 以特定方式格式化电话号码?
- code-generation - Telosys - 如何在当前项目位置之外生成文件?
- jquery - Jquery Bargraph没有正确加载
- javascript - react-native 出现奇怪的 StyleSheet 错误
- node.js - NodeJS express passport-ldapauth 总是返回“无效的用户名/密码”
- ddev - 如何在 ddev 上启用 Apache 模块?
- xdotool - xdotool 中的 POS1 键的名称是什么?