Return task results using firebase-queue

ぐ巨炮叔叔 提交于 2019-12-01 09:24:50
Frank van Puffelen

There definitely is a way to get responses back to the client. We have a good example of that in the Flashlight search integration:

  function doSearch(index, type, query) {
      var ref = new Firebase(URL+'/search');
      var key = ref.child('request').push({ index: index, type: type, query: query }).key();
      console.log('search', key, { index: index, type: type, query: query });
      ref.child('response/'+key).on('value', showResults);
    }

This code runs in the client-side JavaScript application and sends a search term to the server in the line that calls push(). It then "waits" for a response to come back on the last line of the function. The key here is that it listens for a response with the sam push id/key that it used to send the request. That way the request and response match up.

While Firebase Queue doesn't have built-in support for such a "handshake", you can easily build it yourself into the client and server code of your app. When you add a task, you add a request id (adapter from the firebase-queue sample):

var request_id = ref.push().key();
ref.child('queue/tasks').push({ requestId: request_id, foo: 'bar' });

In your task worker, you perform your usual processing and then write the response back into the database with the same request id (adapter from the firebase-queue sample):

var ref = new Firebase('https://<your-firebase>.firebaseio.com/queue');
var responses = new Firebase('https://<your-firebase>.firebaseio.com/responses');
var queue = new Queue(ref, function(data, progress, resolve, reject) {
  // Read and process task data
  console.log(data);

  // Do some work
  progress(50);

  // Finish the task asynchronously
  setTimeout(function() {
    // write the response to the client
    responses.child(data.requestId).set({ allDone: true });
    // tell firebase-queue that we're done
    resolve();
  }, 1000);
});

You do not need to write the requestId in the object. Instead, you can use the following code to return a response. I think it is a bit cleaner.

On the client side: ref.child('queue/tasks').push({foo:'bar'});

The trick is to not sanitize the input. On the server side:

var options = {sanitize:false};

queue = new Queue(firebaseQueueRef, options , function(request, progress, resolve, reject){
   //do some work
   setTimeout(function(){
     resposeRef.child(request._id).set(myResponse);
     resolve();
   }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!