Synchronous/asynchronous responses
Moving from a synchronous to an asynchronous flow is a pattern which LiteFarm intends to use more going forwards. As such, code was created to support this pattern on the backend. In packages/api/src/utils
there is a file called syncAsyncResponse.js
. This file exports one function, called syncAsyncResponse
. The jsdoc comments for this function can be seen below.
/**
* This has an internal timer and returns a function which will send the appropriate response based on the timer.
* @param {Object} res - the response object for the route.
* @param {Number} time - the number of milliseconds before it switches to the async response.
* @return {{sendResponse: ((function(syncCallback: function, asyncCallback: function): Promise<*>)|*)}}
*/
To use this function and pattern on the backend, there are 3 steps, which will be shown using working code from sensorController.js
:
Import it into your code:
const syncAsyncReponse = require('../util/syncAsyncReponse');
Call the function with an optional
timeLimit
parameter (this defaults to 5000, which is the number of milliseconds before the function switches to the asynchronous response):const { sendResponse } = syncAsyncResponse(res, timeLimit);
Whenever you want to return something synchronously/asynchronously within the function call
sendReponse
and provide asynchronousCallback
as well as anasynchronousCallback
. In this example,sendResponse
is being used to either synchronously or asynchronously let the user know that there was a validation error in the file they uploaded:
To use this pattern on the frontend, all you have to do is handle all of the synchronous responses from the API in your code, as well as one special response: the API will return a status of 202 if it has switched to the asynchronous route. By checking for this response status in your code, you can determine when to change the UI to reflect that it is now being handled asynchronously.