"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const rxjs_1 = require("rxjs");
const operators_1 = require("rxjs/operators");
/**
 * Function which executes batchWriteItem operations until all given items (as params) are processed (written).
 * Between each follow-up request (in case of unprocessed items) a delay is interposed calculated by the given backoffTime and throttleTimeSlot.
 * @param dynamoRx
 * @param params containing the items per table to create the batchWrite operation
 * @param backoffTimer used to determine how many time slots the follow-up request should be delayed
 * @param throttleTimeSlot used to calculate the effective wait time
 */
function batchWriteItemsWriteAll(dynamoRx, params, backoffTimer, throttleTimeSlot) {
    return dynamoRx.batchWriteItem(params).pipe(operators_1.mergeMap(response => {
        if (hasUnprocessedItems(response)) {
            // in case of unprocessedItems do a follow-up requests
            return rxjs_1.of(response.UnprocessedItems).pipe(
            // delay before doing the follow-up request
            operators_1.delay(backoffTimer.next().value * throttleTimeSlot), operators_1.mergeMap((unprocessedKeys) => {
                const nextParams = Object.assign({}, params, { RequestItems: unprocessedKeys });
                // call recursively batchWriteItemsWriteAll with the returned UnprocessedItems params
                return batchWriteItemsWriteAll(dynamoRx, nextParams, backoffTimer, throttleTimeSlot);
            }));
        }
        // no follow-up request necessary, return result
        return rxjs_1.of(response);
    }));
}
exports.batchWriteItemsWriteAll = batchWriteItemsWriteAll;
function hasUnprocessedItems(response) {
    if (!response.UnprocessedItems) {
        return false;
    }
    return Object.values(response.UnprocessedItems).some(t => !!t && t.length > 0);
}
exports.hasUnprocessedItems = hasUnprocessedItems;
//# sourceMappingURL=batch-write-utils.js.map