-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_store.hpp
55 lines (40 loc) · 1.43 KB
/
file_store.hpp
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
#pragma once
#include <string>
#include <fstream>
#include <picojson/picojson.h>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
namespace FileStore {
fs::path getFilePath(const std::string& userId, const std::string& folder_path) {
fs::path folder = folder_path.empty() ? fs::current_path() : fs::path(folder_path);
return folder / (userId + ".json");
}
bool writeToFile(const std::string& jsonBody, const std::string& userId, const std::string& folder_path = "") {
fs::path filePath = getFilePath(userId, folder_path);
std::ofstream file(filePath.string());
if (!file.is_open()) {
return false;
}
file << jsonBody;
file.close();
return true;
}
std::string readFromFile(const std::string& userId, const std::string& folder_path = "") {
picojson::value jsonResult;
fs::path filePath = getFilePath(userId, folder_path);
if (!fs::is_regular_file(filePath)) {
return "404";
}
std::ifstream file(filePath.string());
if (!file.is_open()) {
return "404";
}
std::string fileContent((std::istreambuf_iterator<char>(file)), (std::istreambuf_iterator<char>()));
file.close();
std::string err = picojson::parse(jsonResult, fileContent);
if (!err.empty()) {
return "404";
}
return fileContent;
}
}