|
| 1 | +using Magic.IndexedDb.Helpers; |
| 2 | +using Magic.IndexedDb.Interfaces; |
| 3 | +using Magic.IndexedDb.Models; |
| 4 | +using Microsoft.JSInterop; |
| 5 | +using System; |
| 6 | +using System.Collections.Generic; |
| 7 | +using System.Linq; |
| 8 | +using System.Text; |
| 9 | +using System.Threading.Tasks; |
| 10 | + |
| 11 | +namespace Magic.IndexedDb.Extensions |
| 12 | +{ |
| 13 | + internal class MagicJsInvoke |
| 14 | + { |
| 15 | + private readonly IJSObjectReference _jsModule; |
| 16 | + |
| 17 | + public MagicJsInvoke(IJSObjectReference jsModule) |
| 18 | + { |
| 19 | + _jsModule = jsModule; |
| 20 | + } |
| 21 | + |
| 22 | + internal async Task<T?> MagicStreamJsAsync<T>(string functionName, CancellationToken token, params ITypedArgument[] args) |
| 23 | + { |
| 24 | + return await TrueMagicStreamJsAsync<T>(functionName, token, false, args); |
| 25 | + } |
| 26 | + private async Task<T?> TrueMagicStreamJsAsync<T>(string functionName, CancellationToken token, bool isVoid, params ITypedArgument[] args) |
| 27 | + { |
| 28 | + var settings = new MagicJsonSerializationSettings() { UseCamelCase = true }; |
| 29 | + |
| 30 | + var package = new MagicJsPackage |
| 31 | + { |
| 32 | + MethodName = functionName, |
| 33 | + Parameters = MagicSerializationHelper.SerializeObjectsToString(args, settings), |
| 34 | + IsVoid = isVoid |
| 35 | + }; |
| 36 | + |
| 37 | +#if DEBUG |
| 38 | + package.IsDebug = true; |
| 39 | +#endif |
| 40 | + |
| 41 | + using var stream = new MemoryStream(); |
| 42 | + await using (var writer = new StreamWriter(stream, leaveOpen: true)) |
| 43 | + { |
| 44 | + await MagicSerializationHelper.SerializeObjectToStreamAsync(writer, package, settings); |
| 45 | + } |
| 46 | + |
| 47 | + // ✅ Immediately release reference to `package` |
| 48 | + package = null; |
| 49 | + GC.Collect(); |
| 50 | + GC.WaitForPendingFinalizers(); |
| 51 | + |
| 52 | + stream.Position = 0; |
| 53 | + |
| 54 | + var streamRef = new DotNetStreamReference(stream); |
| 55 | + |
| 56 | + // Send to JS |
| 57 | + var responseStreamRef = await _jsModule.InvokeAsync<IJSStreamReference>("streamedJsHandler", token, streamRef); |
| 58 | + |
| 59 | + // 🚀 Convert the stream reference back to JSON in C# |
| 60 | + await using var responseStream = await responseStreamRef.OpenReadStreamAsync(long.MaxValue, token); |
| 61 | + using var reader = new StreamReader(responseStream); |
| 62 | + |
| 63 | + string jsonResponse = await reader.ReadToEndAsync(); |
| 64 | + return MagicSerializationHelper.DeserializeObject<T>(jsonResponse, settings); |
| 65 | + } |
| 66 | + |
| 67 | + internal async Task MagicVoidStreamJsAsync(string functionName, CancellationToken token, params ITypedArgument[] args) |
| 68 | + { |
| 69 | + await TrueMagicStreamJsAsync<bool>(functionName, token, true, args); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + |
| 74 | +} |
0 commit comments