61 lines
1.5 KiB
C++
61 lines
1.5 KiB
C++
#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");
|
|
}
|
|
|
|
if (j.contains("httpPort")) {
|
|
settings.httpPort = j["httpPort"].get<int>();
|
|
} else {
|
|
settings.httpPort = {};
|
|
}
|
|
|
|
return settings;
|
|
}
|
|
|
|
optional<std::string> AppSettings::getId(string_view name){
|
|
for (auto& service : services) {
|
|
if(service.name == name) {
|
|
return service.service;
|
|
}
|
|
}
|
|
return {};
|
|
}
|