import * as tslib_1 from "tslib";
import { of } from 'rxjs';
import { delay, map, mergeMap } from 'rxjs/operators';
export function batchGetItemsFetchAll(dynamoRx, params, backoffTimer, throttleTimeSlot) {
    return dynamoRx.batchGetItems(params)
        .pipe(mergeMap(function (response) {
        if (hasUnprocessedKeys(response)) {
            return of(response.UnprocessedKeys)
                .pipe(delay(backoffTimer.next().value * throttleTimeSlot), mergeMap(function (UnprocessedKeys) {
                var nextParams = tslib_1.__assign({}, params, { RequestItems: UnprocessedKeys });
                return batchGetItemsFetchAll(dynamoRx, nextParams, backoffTimer, throttleTimeSlot);
            }), map(combineBatchGetResponses(response)));
        }
        return of(response);
    }));
}
export function hasUnprocessedKeys(response) {
    if (!response.UnprocessedKeys) {
        return false;
    }
    return Object.values(response.UnprocessedKeys)
        .some(function (t) { return !!t && t.Keys && t.Keys.length > 0; });
}
/**
 * combines a first with a second response. ConsumedCapacity is always from the latter.
 * @param response1
 */
export function combineBatchGetResponses(response1) {
    return function (response2) {
        var tableNames = Object.keys(response1.Responses || {});
        Object.keys(response2.Responses || {})
            .filter(function (tn) { return !tableNames.includes(tn); })
            .forEach(function (tn) { return tableNames.push(tn); });
        var Responses = tableNames
            .reduce(function (u, tableName) {
            var _a;
            return (tslib_1.__assign({}, u, (_a = {}, _a[tableName] = tslib_1.__spread((response1.Responses && response1.Responses[tableName] || []), (response2.Responses && response2.Responses[tableName] || [])), _a)));
        }, {});
        return tslib_1.__assign({}, response2, { Responses: Responses });
    };
}
//# sourceMappingURL=batch-get-utils.js.map