无论何时将新项目添加到Firestore中的集合中,我都编写了以下代码来创建任务。
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
const { CloudTasksClient } = require('@google-cloud/tasks')
exports.moveActivityFromPlanToRecord = () =>
functions
.region('europe-west1')
.firestore.document('Users/{userId}/Activities/{activityId}')
.onCreate(async snapshot => {
const moveTime = snapshot.data()! as MoveTime
if (!moveTime || !moveTime.dueTime) {
console.log("DueTime is empty or null: \n" + moveTime)
return
}
// Get the project ID from the FIREBASE_CONFIG env var
const project = JSON.parse(process.env.FIREBASE_CONFIG!).projectId
const location = 'europe-west1'
const queue = 'activityDateEventChecker'
//queuePath is going to be a string that uniquely identifes the task
const tasksClient = new CloudTasksClient()
const queuePath: string =
tasksClient.queuePath(project, location, queue)
// URL to my callback function and the contents of the payload to deliver
const url = `https://${location}-${project}.cloudfunctions.net/activityDateEventCheckerCallback`
const docPath = snapshot.ref.path
const dueTime = moveTime.dueTime
const payload: MoveTaskPayload = { docPath, dueTime }
console.log(payload)
// build up the configuration for the Cloud Task
const task = {
httpRequest: {
httpMethod: 'POST',
url: url,
body: Buffer.from(JSON.stringify(payload)).toString('base64'),
headers: {
'Content-Type': 'application/json',
},
},
scheduleTime: {
seconds: moveTime.dueTime / 1000
}
}
// enqueue the task in the queue
return tasksClient.createTask({ parent: queuePath, task: task })
})
interface MoveTime extends admin.firestore.DocumentData {
dueTime?: number
}
interface MoveTaskPayload {
docPath: string,
dueTime: number
}
触发函数时(将新的“活动”添加到集合中时),它将引发以下错误:
错误:3 INVALID_ARGUMENT:请求包含无效的参数
这里可能是什么问题?
顺便说一句,应该return
方法的最后一行还是await
任务?
编辑:完全相同的代码现在可以正常工作,而无需我进行任何更改!我只是出于娱乐目的将它与Termux应用程序一起部署,然后它开始工作!
答案 0 :(得分:-1)
我的猜测是您当前的问题源于: `exports.moveActivityFromPlanToRecord =()=> ...
如果删除() =>
部分,则在调用moveActivityFromPlanToRecord
函数时,期望的参数将需要与onCreate()
期望的参数匹配。
那不应该为您解决所有问题,因为onCreate()
带有两个参数function onCreate(snapshot: DataSnapshot, context: EventContext): PromiseLike<any> | any
(因为我在移动设备上,所以从docs而不是源代码中获取了参数)。这意味着onCreate()
函数无法在当前实现中接收参数。
这里可能是什么问题? \顺便说一句,方法的最后一行应该返回任务还是等待它? 几乎可以肯定,您需要返回
Promise
或String
。这是您应了解所有Google Cloud后台功能的基本理解。
可能还有其他问题,但这应该有助于解决您的要求。