File size: 2,295 Bytes
c8cfaf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const { all, get, run } = require('../../db');

function serializeValue(value) {
  return JSON.stringify(value === undefined ? null : value);
}

function deserializeValue(valueJson) {
  if (typeof valueJson !== 'string') return null;
  try {
    return JSON.parse(valueJson);
  } catch {
    return valueJson;
  }
}

class SqliteSettingsStore {
  constructor(db) {
    this.db = db;
  }

  async getAll() {
    const rows = all(this.db, 'SELECT key, value_json FROM app_settings');
    const output = {};
    for (const row of rows) {
      output[row.key] = deserializeValue(row.value_json);
    }
    return output;
  }

  async getMany(keys = []) {
    if (!Array.isArray(keys) || keys.length === 0) {
      return {};
    }

    const result = {};
    for (const key of keys) {
      const normalizedKey = String(key || '').trim();
      if (!normalizedKey) continue;
      const row = get(this.db, 'SELECT value_json FROM app_settings WHERE key = ?', [normalizedKey]);
      if (row) {
        result[normalizedKey] = deserializeValue(row.value_json);
      }
    }
    return result;
  }

  async setMany(values = {}) {
    if (!values || typeof values !== 'object' || Array.isArray(values)) {
      return;
    }

    const now = Date.now();
    for (const [rawKey, value] of Object.entries(values)) {
      const key = String(rawKey || '').trim();
      if (!key) continue;

      run(
        this.db,
        `INSERT INTO app_settings(key, value_json, updated_at)

         VALUES (?, ?, ?)

         ON CONFLICT(key) DO UPDATE SET

           value_json = excluded.value_json,

           updated_at = excluded.updated_at`,
        [key, serializeValue(value), now]
      );
    }
  }

  async deleteMany(keys = []) {
    if (!Array.isArray(keys) || keys.length === 0) {
      return;
    }

    for (const rawKey of keys) {
      const key = String(rawKey || '').trim();
      if (!key) continue;
      run(this.db, 'DELETE FROM app_settings WHERE key = ?', [key]);
    }
  }

  async healthCheck() {
    return {
      backend: 'sqlite',
      connected: true,
      message: 'SQLite app settings store enabled',
    };
  }

  async close() {}
}

module.exports = {
  SqliteSettingsStore,
};