0

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?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
NoNam4
  • 786
  • 4
  • 15

2 Answers2

1

The call for a function queue looks correct:

import { getFunctions  } from 'firebase-admin/functions'

function EnqueueIt() {
    const queuePath = `locations/{location}/functions/{functionName}`;
    const queue = getFunctions().taskQueue(queuePath);
    queue.enqueue({ task, payload });
}

From the description it looks like task is a JavaScript function, and in that case it is not serializable to be transferred to a queue. This explains why only payload as an Object successfully appears in the queue.

Artur A
  • 7,115
  • 57
  • 60
0

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

NoNam4
  • 786
  • 4
  • 15