"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CachedResultService = void 0;
const tslib_1 = require("tslib");
const core_1 = require("@loopback/core");
const repository_1 = require("@loopback/repository");
const bcryptjs_1 = require("bcryptjs");
const moment_1 = tslib_1.__importDefault(require("moment"));
const server_config_service_1 = require("./../server-config/server-config.service");
const cached_result_repository_1 = require("./cached-result.repository");
let CachedResultService = class CachedResultService {
    constructor(cachedResultRepository, serverConfigService) {
        this.cachedResultRepository = cachedResultRepository;
        this.serverConfigService = serverConfigService;
        this.serverConfigService.registerNewConfigurationKey('cachedResultSalt', {
            type: 'string',
            title: 'Cached result secret',
        });
    }
    async getHash(type, args) {
        return bcryptjs_1.hash(type + JSON.stringify(args), await this.serverConfigService.get('cachedResultSalt', bcryptjs_1.genSalt));
    }
    async getResult(type, args, defaultResult, validity = moment_1.default.duration(1, 'month')) {
        const hashedArgs = await this.getHash(type, args);
        const id = type + ':' + hashedArgs;
        let cachedResult = undefined;
        try {
            const cachedResultObj = await this.cachedResultRepository.findById(id);
            if (cachedResultObj) {
                cachedResult = cachedResultObj.value;
            }
            // eslint-disable-next-line no-empty
        }
        catch (error) { }
        if (!cachedResult) {
            cachedResult = await defaultResult();
            const validityDate = moment_1.default();
            validityDate.add(validity);
            await this.cachedResultRepository.create({
                id,
                type,
                hash: hashedArgs,
                args,
                value: cachedResult,
                endValidity: validityDate.toISOString(),
            });
        }
        return cachedResult;
    }
};
CachedResultService = tslib_1.__decorate([
    tslib_1.__param(0, repository_1.repository(cached_result_repository_1.CachedResultRepository)),
    tslib_1.__param(1, core_1.service(server_config_service_1.ServerConfigService)),
    tslib_1.__metadata("design:paramtypes", [cached_result_repository_1.CachedResultRepository,
        server_config_service_1.ServerConfigService])
], CachedResultService);
exports.CachedResultService = CachedResultService;
//# sourceMappingURL=cached-result.service.js.map