added JSON support to select the services
This commit is contained in:
54
src/json_settings.cpp
Normal file
54
src/json_settings.cpp
Normal file
@@ -0,0 +1,54 @@
|
||||
#include <fstream>
|
||||
#include <format>
|
||||
#include "json.hpp"
|
||||
#include "json_settings.h"
|
||||
|
||||
using namespace std;
|
||||
using json = nlohmann::json;
|
||||
|
||||
expected<AppSettings, string> AppSettings::loadAppSettings() {
|
||||
constexpr char settings_file[] = "static/settings.json";
|
||||
ifstream file(settings_file);
|
||||
if (!file.is_open()) {
|
||||
return unexpected(format("Failed to open {}",settings_file));
|
||||
}
|
||||
|
||||
// Parse the JSON
|
||||
json j;
|
||||
try {
|
||||
file >> j;
|
||||
} catch (const json::parse_error& e) {
|
||||
return unexpected(format("Failed to parse JSON {}",e.what()));
|
||||
}
|
||||
|
||||
if (!j.contains("services") || !j["services"].is_array()) {
|
||||
return unexpected("JSON does not contain an array called 'services'");
|
||||
}
|
||||
|
||||
AppSettings settings;
|
||||
|
||||
for (const auto& item : j["services"]) {
|
||||
if (item.is_array() && item.size() == 2) {
|
||||
Service service = {
|
||||
item[0].get<std::string>(),
|
||||
item[1].get<std::string>()
|
||||
};
|
||||
settings.services.push_back(service);
|
||||
}
|
||||
}
|
||||
|
||||
if (settings.services.empty()){
|
||||
return unexpected("'services' array in JSON file is empty");
|
||||
}
|
||||
|
||||
return settings;
|
||||
}
|
||||
|
||||
optional<const std::string&> AppSettings::getId(string_view name){
|
||||
for (auto& service : services) {
|
||||
if(service.name == name) {
|
||||
return service.service;
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
Reference in New Issue
Block a user