import { values as objValues } from 'lodash';
import { map } from 'rxjs/operators';
import { Mapper } from '../../../mapper/mapper';
import { resolveAttributeNames } from '../../expression/functions/attribute-names.function';
import { BaseRequest } from '../base.request';
export class GetRequest extends BaseRequest {
    constructor(dynamoRx, modelClazz, tableName, partitionKey, sortKey) {
        super(dynamoRx, modelClazz, tableName);
        const hasSortKey = this.metaData.getSortKey() !== null;
        if (hasSortKey && (sortKey === null || sortKey === undefined)) {
            throw new Error(`please provide the sort key for attribute ${this.metaData.getSortKey()}`);
        }
        const keyAttributeMap = {};
        // partition key
        const partitionKeyValue = Mapper.toDbOne(partitionKey, this.metaData.forProperty(this.metaData.getPartitionKey()));
        if (partitionKeyValue === null) {
            throw new Error('please provide an acutal value for partition key, got null');
        }
        keyAttributeMap[this.metaData.getPartitionKey()] = partitionKeyValue;
        // sort key
        if (hasSortKey) {
            const sortKeyValue = Mapper.toDbOne(sortKey, this.metaData.forProperty(this.metaData.getSortKey()));
            if (sortKeyValue === null) {
                throw new Error('please provide an actual value for sort key, got null');
            }
            keyAttributeMap[this.metaData.getSortKey()] = sortKeyValue;
        }
        this.params.Key = keyAttributeMap;
    }
    consistentRead(consistendRead) {
        this.params.ConsistentRead = consistendRead;
        return this;
    }
    returnConsumedCapacity(level) {
        this.params.ReturnConsumedCapacity = level;
        return this;
    }
    projectionExpression(...attributesToGet) {
        const resolved = attributesToGet.map(attr => resolveAttributeNames(attr));
        this.params.ProjectionExpression = resolved.map(attr => attr.placeholder).join(', ');
        objValues(resolved).forEach(r => {
            this.params.ExpressionAttributeNames = Object.assign({}, this.params.ExpressionAttributeNames, r.attributeNames);
        });
        return this;
    }
    execFullResponse() {
        return this.dynamoRx.getItem(this.params).pipe(map(getItemResponse => {
            const response = Object.assign({}, getItemResponse);
            if (getItemResponse.Item) {
                response.Item = Mapper.fromDb(getItemResponse.Item, this.modelClazz);
            }
            else {
                response.Item = null;
            }
            return response;
        }));
    }
    exec() {
        return this.dynamoRx.getItem(this.params).pipe(map(response => {
            if (response.Item) {
                return Mapper.fromDb(response.Item, this.modelClazz);
            }
            else {
                return null;
            }
        }));
    }
}
//# sourceMappingURL=get.request.js.map