SPB Git

Repository Public

SettingsStore.swift 1.3 KB 28 lines swift

1import Foundation23/// Key → JSON settings. Values are `Codable`; a value that fails to decode (corrupt or from a4/// newer version) is reported as missing rather than crashing, and the UI falls back to defaults.5public final class SettingsStore: Sendable {6    private let db: SQLiteDatabase7    private let encoder = JSONEncoder()8    private let decoder = JSONDecoder()910    public init(database: SQLiteDatabase) { self.db = database }1112    public func get<T: Decodable>(_ key: String, as type: T.Type = T.self) -> T? {13        guard let row = try? db.query("SELECT value_json FROM settings WHERE key=?", [.text(key)]).first,14              let json = row.string("value_json") else { return nil }15        return try? decoder.decode(T.self, from: Data(json.utf8))16    }1718    public func set<T: Encodable>(_ key: String, _ value: T) throws {19        let json = String(decoding: try encoder.encode(value), as: UTF8.self)20        try db.execute("INSERT INTO settings(key, value_json, updated_at) VALUES(?,?,?) ON CONFLICT(key) DO UPDATE SET value_json=excluded.value_json, updated_at=excluded.updated_at",21                       [.text(key), .text(json), SQLiteValue(Date())])22    }2324    public func remove(_ key: String) throws {25        try db.execute("DELETE FROM settings WHERE key=?", [.text(key)])26    }27}28
Files main
Menu

Theme