-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathNodeConnector.cs
More file actions
120 lines (96 loc) · 3.47 KB
/
NodeConnector.cs
File metadata and controls
120 lines (96 loc) · 3.47 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
using System.Text;
using System.Text.Json;
using PowerSync.Common.Client;
using PowerSync.Common.Client.Connection;
using PowerSync.Common.DB.Crud;
namespace MAUITodo.Data;
public class NodeConnector : IPowerSyncBackendConnector
{
private string StorageFilePath => Path.Combine(FileSystem.AppDataDirectory, "user_id.txt");
private readonly HttpClient _httpClient;
public string BackendUrl { get; }
public string PowerSyncUrl { get; }
public string UserId { get; private set; }
private string? clientId;
public NodeConnector()
{
_httpClient = new HttpClient();
// Load or generate User ID
UserId = LoadOrGenerateUserId();
BackendUrl = "http://localhost:6060";
PowerSyncUrl = "http://localhost:8080";
clientId = null;
}
public string LoadOrGenerateUserId()
{
if (File.Exists(StorageFilePath))
{
return File.ReadAllText(StorageFilePath);
}
string newUserId = Guid.NewGuid().ToString();
File.WriteAllText(StorageFilePath, newUserId);
return newUserId;
}
public async Task<PowerSyncCredentials?> FetchCredentials()
{
string tokenEndpoint = "api/auth/token";
string url = $"{BackendUrl}/{tokenEndpoint}?user_id={UserId}";
HttpResponseMessage response = await _httpClient.GetAsync(url);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"Received {response.StatusCode} from {tokenEndpoint}: {await response.Content.ReadAsStringAsync()}");
}
string responseBody = await response.Content.ReadAsStringAsync();
var jsonResponse = JsonSerializer.Deserialize<Dictionary<string, string>>(responseBody);
if (jsonResponse == null || !jsonResponse.ContainsKey("token"))
{
throw new Exception("Invalid response received from authentication endpoint.");
}
return new PowerSyncCredentials(PowerSyncUrl, jsonResponse["token"]);
}
public async Task UploadData(IPowerSyncDatabase database)
{
CrudTransaction? transaction;
try
{
transaction = await database.GetNextCrudTransaction();
}
catch (Exception ex)
{
Console.WriteLine($"UploadData Error: {ex.Message}");
return;
}
if (transaction == null)
{
return;
}
clientId ??= await database.GetClientId();
try
{
var batch = new List<object>();
foreach (var operation in transaction.Crud)
{
batch.Add(new
{
op = operation.Op.ToString(),
table = operation.Table,
id = operation.Id,
data = operation.OpData
});
}
var payload = JsonSerializer.Serialize(new { batch });
var content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _httpClient.PostAsync($"{BackendUrl}/api/data", content);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"Received {response.StatusCode} from /api/data: {await response.Content.ReadAsStringAsync()}");
}
await transaction.Complete();
}
catch (Exception ex)
{
Console.WriteLine($"UploadData Error: {ex.Message}");
throw;
}
}
}