import * as tslib_1 from "tslib";
import { of } from 'rxjs';
import { delay, mergeMap } from '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
 */
export function batchWriteItemsWriteAll(dynamoRx, params, backoffTimer, throttleTimeSlot) {
    return dynamoRx.batchWriteItem(params).pipe(mergeMap(function (response) {
        if (hasUnprocessedItems(response)) {
            // in case of unprocessedItems do a follow-up requests
            return of(response.UnprocessedItems).pipe(
            // delay before doing the follow-up request
            delay(backoffTimer.next().value * throttleTimeSlot), mergeMap(function (unprocessedKeys) {
                var nextParams = tslib_1.__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 of(response);
    }));
}
export function hasUnprocessedItems(response) {
    if (!response.UnprocessedItems) {
        return false;
    }
    return Object.values(response.UnprocessedItems).some(function (t) { return !!t && t.length > 0; });
}
//# sourceMappingURL=batch-write-utils.js.map