Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Current »

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. 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:

    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):

    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:

    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' } },
          );
        },
      );
    }

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.

  • No labels