using System.Collections.Immutable; using System.Text.Json.Nodes; using Connected.Net; using Connected.ServiceModel.Client.Net; using Connected.ServiceModel.Client.Subscription; namespace Connected.ServiceModel.Client.Data.Remote; internal sealed class RemoteTableService { //TODO:load it from config or environment. private const string AccessToken = "Temp"; public RemoteTableService(IHttpService http, IConnectedServer server, ISubscriptionService subscription) { Http = http; Server = server; Subscription = subscription; } private IHttpService Http { get; } private IConnectedServer Server { get; } private ISubscriptionService Subscription { get; } private int SubscriptionId { get; set; } public async Task Query(string commandText) { await Initialize(); var url = await Server.SelectUrl(new ConnectedServerUrlArgs { Kind = ConnectedUrlKind.TableStorage }); if (await Http.Post($"{url}/query", new QueryTableArgs { CommandText = commandText, AccessToken = AccessToken, Subscription = SubscriptionId }) is not JsonArray result) return new JsonArray(); return result; } public async Task> QueryColumns(string tableName) { await Initialize(); var url = await Server.SelectUrl(new ConnectedServerUrlArgs { Kind = ConnectedUrlKind.TableStorage }); if (await Http.Post>($"{url}/queryColumns", new TableSchemaArgs { TableName = tableName, AccessToken = AccessToken, Subscription = SubscriptionId }) is not List result) return ImmutableList.Empty; return result.ToImmutableList(); } public async Task TableExists(string tableName) { await Initialize(); var url = await Server.SelectUrl(new ConnectedServerUrlArgs { Kind = ConnectedUrlKind.TableStorage }); return await Http.Post($"{url}/tableExists", new TableSchemaArgs { TableName = tableName, AccessToken = AccessToken, Subscription = SubscriptionId }); } public async Task Update(string commandText) { await Initialize(); var url = await Server.SelectUrl(new ConnectedServerUrlArgs { Kind = ConnectedUrlKind.TableStorage }); await Http.Post($"{url}/update", new UpdateTableArgs { CommandText = commandText, AccessToken = AccessToken, Subscription = SubscriptionId }); } public async Task CreateTable(string tableName, List columns) { await Initialize(); var url = await Server.SelectUrl(new ConnectedServerUrlArgs { Kind = ConnectedUrlKind.TableStorage }); await Http.Post($"{url}/createTable", new CreateTableArgs { Name = tableName, Columns = columns, AccessToken = AccessToken, Subscription = SubscriptionId }); } private async Task Initialize() { if (SubscriptionId > 0) return; if (await Subscription.Select() is not ISubscription subscription) throw new NullReferenceException(nameof(ISubscription)); SubscriptionId = subscription.Id; } }