Return task results using firebase-queue

后端 未结 2 2080
清酒与你
清酒与你 2021-01-14 17:39

I am working on a mobile application using Firebase. In the mobile app, I need to register a user based on his/her mobile number similar to Whatsapp. I intend to use Nexmo t

相关标签:
2条回答
  • 2021-01-14 17:49

    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);
    });
    
    0 讨论(0)
  • 2021-01-14 17:58

    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();
       }
    });
    
    0 讨论(0)
提交回复
热议问题