import { map, tap } from 'rxjs/operators';
import { randomExponentialBackoffTimer } from '../../../helper';
import { createLogger } from '../../../logger/logger';
import { createToKeyFn, fromDb } from '../../../mapper';
import { batchGetItemsFetchAll } from '../../batchget/batch-get-utils';
import { BATCH_GET_DEFAULT_TIME_SLOT, BATCH_GET_MAX_REQUEST_ITEM_COUNT } from '../../batchget/batch-get.const';
import { BaseRequest } from '../base.request';
export class BatchGetSingleTableRequest extends BaseRequest {
    constructor(dynamoRx, modelClazz, keys) {
        super(dynamoRx, modelClazz);
        this.mapResponse = (response) => {
            let items = [];
            if (response.Responses && Object.keys(response.Responses).length && response.Responses[this.tableName]) {
                const mapped = response.Responses[this.tableName].map(attributeMap => fromDb(attributeMap, this.modelClazz));
                items = mapped;
            }
            return {
                Items: items,
                UnprocessedKeys: response.UnprocessedKeys,
                ConsumedCapacity: response.ConsumedCapacity,
            };
        };
        this.logger = createLogger('dynamo.request.BatchGetSingleTableRequest', modelClazz);
        if (keys.length > BATCH_GET_MAX_REQUEST_ITEM_COUNT) {
            throw new Error(`you can request at max ${BATCH_GET_MAX_REQUEST_ITEM_COUNT} items per request`);
        }
        this.params.RequestItems = {
            [this.tableName]: {
                Keys: keys.map(createToKeyFn(modelClazz)),
            },
        };
    }
    consistentRead(value = true) {
        this.params.RequestItems[this.tableName].ConsistentRead = value;
        return this;
    }
    execNoMap(backoffTimer = randomExponentialBackoffTimer, throttleTimeSlot = BATCH_GET_DEFAULT_TIME_SLOT) {
        return this.fetch(backoffTimer, throttleTimeSlot);
    }
    execFullResponse(backoffTimer = randomExponentialBackoffTimer, throttleTimeSlot = BATCH_GET_DEFAULT_TIME_SLOT) {
        return this.fetch(backoffTimer, throttleTimeSlot).pipe(map(this.mapResponse), tap(response => this.logger.debug('mapped items', response.Items)));
    }
    exec(backoffTimer = randomExponentialBackoffTimer, throttleTimeSlot = BATCH_GET_DEFAULT_TIME_SLOT) {
        return this.fetch(backoffTimer, throttleTimeSlot).pipe(map(this.mapResponse), map(r => r.Items), tap(items => this.logger.debug('mapped items', items)));
    }
    fetch(backoffTimer = randomExponentialBackoffTimer, throttleTimeSlot = BATCH_GET_DEFAULT_TIME_SLOT) {
        this.logger.debug('request', this.params);
        return batchGetItemsFetchAll(this.dynamoRx, Object.assign({}, this.params), backoffTimer(), throttleTimeSlot).pipe(tap(response => this.logger.debug('response', response)));
    }
}
//# sourceMappingURL=batch-get-single-table.request.js.map