Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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
languagejs
/**
 * 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:

  1. Import it into your code:

    Code Block
    languagejs
    const syncAsyncReponse = require('../util/syncAsyncReponse');

  2. 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
    languagejs
    const { sendResponse } = syncAsyncResponse(res, timeLimit);

  3. Whenever you want to return something synchronously/asynchronously within the function call sendReponse and provide a synchronousCallback as well as an asynchronousCallback. 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
    languagejs
    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' } },
          );
        },
      );
    }

...