5

I've written the below code to create a task whenever a new item is added to a collection in the 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
}

When the function is triggered (when a new "activity" is added to the collection), it throws the following error:

Error: 3 INVALID_ARGUMENT: Request contains an invalid argument

What could be the problem here?
BTW, should the last line in the method return the task, or await it?


EDIT: The exact same code is now working without me changing anything! I just deployed it with the Termux app just for fun, and after that it started working!

SIMMORSAL
  • 1,402
  • 1
  • 16
  • 32
  • share the complete logs and the line on which error occurs, is it the post method or before it? – ahmadalibaloch Jun 28 '20 at 13:06
  • Did you find out what was going wrong ? I'm getting the same error. The stack trace involve GRPC. I was thinking it's mabye related to this : body: Buffer.from(JSON.stringify(payload)).toString('base64') but I've no clue... – Thomas Aug 27 '20 at 14:34

1 Answers1

0

My guess is your current issue stems from: `exports.moveActivityFromPlanToRecord = () => ...

If you remove the () => part then when the moveActivityFromPlanToRecord function is called, the expected parameters will need to match what onCreate() expects.

That shouldn't solve everything for you because onCreate() takes two parameters, function onCreate(snapshot: DataSnapshot, context: EventContext): PromiseLike<any> | any (took that from the docs rather than source code because I'm on mobile). Which means that there is no way for the onCreate() function to receive parameters in your current implementation.

What could be the problem here? \ BTW, should the last line in the method return the task, or await it? Almost certain that you need to return a Promise or String. That's a basic understanding you should read about for all background Google Cloud functions.

There may be other issues, but that should help resolve what your asking for.

Shalbert
  • 1,044
  • 11
  • 17