// cache.js
// Copyright (C) 2022 DTP Technologies, LLC
// License: Apache-2.0

'use strict';

const { SiteService } = require('../../lib/site-lib');

class CacheService extends SiteService {

  constructor (dtp) {
    super(dtp, module.exports);
  }

  async set (name, value) {
    return this.dtp.redis.set(name, value);
  }

  async setEx (name, seconds, value) {
    return this.dtp.redis.setex(name, seconds, value);
  }

  async get (name) {
    return this.dtp.redis.get(name);
  }

  async setObject (name, value) {
    return this.dtp.redis.set(name, JSON.stringify(value));
  }

  async setObjectEx (name, seconds, value) {
    return this.dtp.redis.setex(name, seconds, JSON.stringify(value));
  }

  async getObject (name) {
    const value = await this.dtp.redis.get(name);
    if (!value) {
      return; // undefined
    }
    return JSON.parse(value);
  }

  async del (name) {
    return this.dtp.redis.del(name);
  }

  getKeys (pattern) {
    return new Promise((resolve, reject) => {
      return this.dtp.redis.keys(pattern, (err, response) => {
        if (err) {
          return reject(err);
        }
        return resolve(response);
      });
    });
  }
}

module.exports = {
  slug: 'cache',
  name: 'cache',
  create: (dtp) => { return new CacheService(dtp); },
};