68 lines
2.3 KiB
Java
68 lines
2.3 KiB
Java
package su.xserver.iikocon;
|
|
|
|
import io.vertx.core.Future;
|
|
import io.vertx.core.json.JsonObject;
|
|
import io.vertx.sqlclient.Pool;
|
|
import io.vertx.sqlclient.templates.SqlTemplate;
|
|
|
|
import java.util.Map;
|
|
|
|
public class SettingsService {
|
|
private final Pool pool;
|
|
|
|
public SettingsService(Pool pool) { this.pool = pool; }
|
|
|
|
public Future<Void> initDatabase() {
|
|
String createTable = """
|
|
CREATE TABLE IF NOT EXISTS app_settings (
|
|
setting_key VARCHAR(255) PRIMARY KEY,
|
|
setting_value TEXT
|
|
)
|
|
""";
|
|
return pool.query(createTable).execute()
|
|
.compose(v -> setIfAbsent("site_name", "Admin Panel"))
|
|
.compose(v -> setIfAbsent("site_description", "Powerful administration dashboard"))
|
|
.compose(v -> setIfAbsent("theme", "light"))
|
|
.compose(v -> setIfAbsent("items_per_page", "20"))
|
|
.compose(v -> setIfAbsent("enable_registration", "true"))
|
|
.compose(v -> setIfAbsent("maintenance_mode", "false"))
|
|
.compose(v -> setIfAbsent("default_language", "en"))
|
|
.compose(v -> setIfAbsent("session_timeout_minutes", "60"))
|
|
.compose(v -> setIfAbsent("logo_url", "/assets/logo.png"))
|
|
.mapEmpty();
|
|
}
|
|
|
|
private Future<Void> setIfAbsent(String key, String defaultValue) {
|
|
return get(key).compose(existing -> {
|
|
if (existing == null) {
|
|
return set(key, defaultValue);
|
|
}
|
|
return Future.succeededFuture();
|
|
});
|
|
}
|
|
|
|
public Future<String> get(String key) {
|
|
return SqlTemplate.forQuery(pool, "SELECT setting_value FROM app_settings WHERE setting_key = #{key}")
|
|
.execute(Map.of("key", key))
|
|
.map(rows -> rows.iterator().hasNext() ? rows.iterator().next().getString("setting_value") : null);
|
|
}
|
|
|
|
public Future<Void> set(String key, String value) {
|
|
return SqlTemplate.forUpdate(pool,
|
|
"INSERT INTO app_settings (setting_key, setting_value) VALUES (#{key}, #{value}) " +
|
|
"ON DUPLICATE KEY UPDATE setting_value = #{value}")
|
|
.execute(Map.of("key", key, "value", value))
|
|
.mapEmpty();
|
|
}
|
|
|
|
public Future<JsonObject> getAll() {
|
|
return pool.query("SELECT setting_key, setting_value FROM app_settings")
|
|
.execute()
|
|
.map(rows -> {
|
|
JsonObject json = new JsonObject();
|
|
rows.forEach(row -> json.put(row.getString("setting_key"), row.getString("setting_value")));
|
|
return json;
|
|
});
|
|
}
|
|
}
|