"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteItem = exports.putItem = exports.queryItems = exports.getItem = exports.overrideDynamoDbDocumentClientWithTestClient = void 0;
const ramda_1 = require("ramda");
const errors_1 = require("../errors");
const logging_1 = require("../logging");
const utils_1 = require("../utils");
const initializeDynamoDbDocumentClient_1 = require("./initializeDynamoDbDocumentClient");
let documentClient = (0, initializeDynamoDbDocumentClient_1.initializeDynamoDbDocumentClient)();
const overrideDynamoDbDocumentClientWithTestClient = (testDocumentClient) => {
    documentClient = testDocumentClient;
    throw errors_1.TechnicalError.testOnlyFunctionWasCalled('overrideDynamoDbDocumentClientWithTestClient');
};
exports.overrideDynamoDbDocumentClientWithTestClient = overrideDynamoDbDocumentClientWithTestClient;
const getItem = async (searchParams) => {
    /*
     * All Dfns documents contain a property called info at their root.
     * Data is stored inside this property and everything outside is either a key or an index.
     * At the moment public key tables don't respect the convention, and this code is adapted
     * to ignore this temporart lack of coherence
     */
    const shallowItem = await documentClient.get(searchParams).promise();
    const compliantItem = (0, ramda_1.path)(['Item', 'info'], shallowItem);
    if (compliantItem) {
        return compliantItem;
    }
    else if (shallowItem) {
        return shallowItem;
    }
    else {
        throw errors_1.NotFoundError.itemNotFoundInDynamoDb(searchParams);
    }
};
exports.getItem = getItem;
const queryItems = async (searchParams) => {
    var _a;
    const searchResults = await documentClient.query(searchParams).promise();
    if ((0, utils_1.isNonEmptyArray)(searchResults.Items)) {
        return (_a = searchResults.Items) === null || _a === void 0 ? void 0 : _a.map((0, ramda_1.path)(['info']));
    }
    else {
        throw errors_1.NotFoundError.itemsNotFoundInDynamoDb(searchParams);
    }
};
exports.queryItems = queryItems;
const putItem = (item) => {
    return documentClient
        .put(item)
        .promise()
        .then(() => {
        return true;
    })
        .catch((error) => {
        logging_1.logger.error(`putItem: Failed to save item to table ${item.TableName}`);
        logging_1.logger.error(`putItem: Unable to create item`, { payload: { error } });
        return false;
    });
};
exports.putItem = putItem;
const deleteItem = (item) => {
    return documentClient
        .delete(item)
        .promise()
        .then(() => {
        return true;
    })
        .catch((error) => {
        logging_1.logger.error(`deleteItem: Failed to save item to table ${item.TableName}`);
        logging_1.logger.error(`deleteItem: Unable to create item`, { payload: { error } });
        return false;
    });
};
exports.deleteItem = deleteItem;
//# sourceMappingURL=dynamodb.js.map