"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var CacheService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheService = void 0;
const common_1 = require("@nestjs/common");
const core_1 = require("@nestjs/core");
const file_system_cache_1 = __importDefault(require("file-system-cache"));
const cache_decorator_1 = require("./cache.decorator");
let CacheService = CacheService_1 = class CacheService {
    constructor(discoveryService, metadataScanner, reflector) {
        this.discoveryService = discoveryService;
        this.metadataScanner = metadataScanner;
        this.reflector = reflector;
        this.logger = new common_1.Logger(CacheService_1.name);
        this.cacheManager = (0, file_system_cache_1.default)({
            basePath: './.cache',
            ns: '@Cache',
        });
    }
    onModuleInit() {
        const instanceWrappers = this.discoveryService.getProviders();
        instanceWrappers
            .filter(wrapper => wrapper.isDependencyTreeStatic() && !!wrapper.instance)
            .forEach(wrapper => {
            this.metadataScanner.scanFromPrototype(wrapper.instance, Object.getPrototypeOf(wrapper.instance), (methodName) => {
                this.registerCache(wrapper.instance, methodName);
            });
        });
    }
    extractKey(cacheKey, args) {
        return typeof cacheKey === 'function' ? cacheKey(...args) : cacheKey;
    }
    registerCache(instance, methodName) {
        const logger = this.logger;
        const methodRef = instance[methodName];
        const options = this.reflector.get(cache_decorator_1.CACHE_DECORATOR, methodRef);
        if (!options)
            return;
        const cacheManager = this.cacheManager;
        const extractKey = this.extractKey;
        instance[methodName] = function (...args) {
            return __awaiter(this, void 0, void 0, function* () {
                const cacheKey = extractKey(options.key, args);
                const cachedValue = yield cacheManager.get(cacheKey);
                if (cachedValue) {
                    return cachedValue;
                }
                else {
                    try {
                        const liveData = yield methodRef.apply(this, args);
                        yield cacheManager.set(cacheKey, liveData);
                        return liveData;
                    }
                    catch (e) {
                        logger.error(`@Cache error for ${instance.constructor.name}#${methodName}`, e);
                    }
                }
            });
        };
    }
};
CacheService = CacheService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, common_1.Inject)(core_1.DiscoveryService)),
    __param(1, (0, common_1.Inject)(core_1.MetadataScanner)),
    __param(2, (0, common_1.Inject)(core_1.Reflector)),
    __metadata("design:paramtypes", [core_1.DiscoveryService,
        core_1.MetadataScanner,
        core_1.Reflector])
], CacheService);
exports.CacheService = CacheService;
//# sourceMappingURL=cache.service.js.map