Search code examples
node.jsfirebasegoogle-cloud-functionstask-queuegoogle-tasks

Firebase tasks pass function as queue payload


I'm trying to create a generic task queue in firebase.

Following docs I'm supposed to create a new queue for each function I need but I want to create a generic queue that will accept any function.

I've tryed creating something like this

export async function enqueue<T>(
  task: any, // this will be the function that will be executed in the queue
  payload: T // this is all params for this function
): Promise<any> {
  if ( isDev() ) {
    // in dev mode this works fine
    return await task( payload )
  }

  const FUNCTIONS_REGION = process.env.FUNCTIONS_REGION
  const queue = functions.taskQueue(
    `locations/${ FUNCTIONS_REGION }/functions/queue`
  )
  return await Promise.all( [ queue.enqueue( {
    task,
    payload
  }, {
    dispatchDeadlineSeconds: 60 * 5 // 5 minutes
  } ) ] )
}

.......

exports.queue = functions
  .region( FUNCTIONS_REGION! )
  .tasks.taskQueue( queuesConfig )
  .onDispatch( async ( data: QueueType ) => {
    const {
      task,
      payload
    } = data
    // here's my problem, in GCP console, the task is showing as undefined
    console.log( 'task', task )
    // but the payload is ok, everything is there
    console.log( 'payload', payload )
    await task( payload )
  } )

How can I pass the function as data for my queue?


Solution

  • Ok, I've figured out what was the error... when firebase enqueues any task it does a http request to cloud tasks API and this does not support functions as parameters because all data is a json so my 'task' variable was always undefined. Locally this works because JS accepts functions as parameters.

    I ended using a functions object and 'taks' is an object key