"use strict";
/**
 * @adonisjs/session
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.RedisDriver = void 0;
/// <reference path="../../adonis-typings/index.ts" />
const utils_1 = require("@poppinss/utils");
const helpers_1 = require("@poppinss/utils/build/helpers");
/**
 * File driver to read/write session to filesystem
 */
class RedisDriver {
    constructor(config, redis) {
        this.config = config;
        this.redis = redis;
        /**
         * Convert milliseconds to seconds
         */
        this.ttl = Math.round((typeof this.config.age === 'string' ? helpers_1.string.toMs(this.config.age) : this.config.age) / 1000);
        if (!this.config.redisConnection) {
            throw new utils_1.Exception('Missing redisConnection for session redis driver inside "config/session" file', 500, 'E_INVALID_SESSION_DRIVER_CONFIG');
        }
    }
    /**
     * Returns instance of the redis connection
     */
    getRedisConnection() {
        return this.redis.connection(this.config.redisConnection);
    }
    /**
     * Returns file contents. A new file will be created if it's
     * missing.
     */
    async read(sessionId) {
        const contents = await this.getRedisConnection().get(sessionId);
        if (!contents) {
            return null;
        }
        const verifiedContents = new helpers_1.MessageBuilder().verify(contents, sessionId);
        if (typeof verifiedContents !== 'object') {
            return null;
        }
        return verifiedContents;
    }
    /**
     * Write session values to a file
     */
    async write(sessionId, values) {
        if (typeof values !== 'object') {
            throw new Error('Session file driver expects an object of values');
        }
        await this.getRedisConnection().setex(sessionId, this.ttl, new helpers_1.MessageBuilder().build(values, undefined, sessionId));
    }
    /**
     * Cleanup session file by removing it
     */
    async destroy(sessionId) {
        await this.getRedisConnection().del(sessionId);
    }
    /**
     * Updates the value expiry
     */
    async touch(sessionId) {
        await this.getRedisConnection().expire(sessionId, this.ttl);
    }
}
exports.RedisDriver = RedisDriver;
