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.
Code Block | ||
---|---|---|
| ||
/**
* 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:
Code Block language js 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):Code Block language js 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:Code Block language js if (errors.length > 0) { return await sendResponse( () => { return res .status(400) .send({ error_type: 'validation_failure', errors, is_validation_error: true }); }, async () => { return await sendSensorNotification( user_id, farm_id, SensorNotificationTypes.SENSOR_BULK_UPLOAD_FAIL, { error_download: { errors, file_name: 'sensor-upload-outcomes.txt' } }, ); }, ); }
...