Skip to content

Commit

Permalink
♻️ Add route and http context to ServerLoad func
Browse files Browse the repository at this point in the history
  • Loading branch information
koeeenig committed Feb 8, 2024
1 parent fa76c6b commit 1716ca0
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 27 deletions.
2 changes: 1 addition & 1 deletion src/BlazeKit.Static/BlazeKit.Static.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Html.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Markdig" Version="0.33.0" />
<PackageReference Include="YamlDotNet" Version="15.1.0" />
</ItemGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<ProjectReference Include="..\BlazeKit.Hydration\BlazeKit.Hydration.csproj" />
</ItemGroup>
</Project>
1 change: 1 addition & 0 deletions src/BlazeKit.Web/BlazeKit.Web.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="8.0.0" />
</ItemGroup>

Expand Down
25 changes: 7 additions & 18 deletions src/BlazeKit.Web/Components/PageComponentBase.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
using BlazeKit.Hydration;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.AspNetCore.Http;

namespace BlazeKit.Web.Components;
public abstract class PageComponentBase<TResult> : IComponent, IPageLoad<TResult> where TResult : PageDataBase
{
[Inject] required public DataHydrationContext HydrationContext { get; init; }

[Inject] required public NavigationManager NavigationManager { get; init; }
[CascadingParameter] private HttpContext? Context { get; set; }

private RenderFragment renderFragment;
private readonly string dataKey;
private RenderHandle renderHandle;
Expand Down Expand Up @@ -54,7 +57,8 @@ public async Task SetParametersAsync(ParameterView parameters)

if(IsServer())
{
var data = await this.ServerLoadAsync();
var route = new Uri(NavigationManager.Uri);
var data = await this.ServerLoadAsync(route, Context);
if(data != null)
{
this.data = data;
Expand All @@ -79,27 +83,12 @@ protected virtual void BuildRenderTree(RenderTreeBuilder builder)
// but instead should invoke the _renderFragment field.
}

protected virtual Task<TResult> ServerLoadAsync()
protected virtual Task<TResult> ServerLoadAsync(Uri route, HttpContext? context)
{
return Task.FromResult<TResult>(default(TResult));
}


void Render(RenderTreeBuilder builder)
{
// decorate the ChildContent with a CascadingValue contianing the PageData
builder.OpenComponent<global::Microsoft.AspNetCore.Components.CascadingValue<TResult>>(0);
builder.AddComponentParameter(1, "Value", this.PageData);
builder.AddComponentParameter(1, "Name", "PageData");
builder.AddComponentParameter(2, "ChildContent", renderFragment);
builder.CloseComponent();
}

protected Task<T> LoadPageDataAsync<T>(T fallback)
{
return HydrationContext.GetAsync<T>(this.dataKey, fallback);
}

private bool IsServer()
{
return !OperatingSystem.IsBrowser();
Expand Down
8 changes: 2 additions & 6 deletions src/BlazeKit.Web/IPageLoad.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace BlazeKit.Web;

internal interface IPageLoad<TPageData>
{
virtual Task<TPageData> ServerLoadAsync() => Task.FromResult(default(TPageData));
virtual Task<TPageData> ServerLoadAsync(Uri route, HttpContext? context) => Task.FromResult(default(TPageData));
}
29 changes: 29 additions & 0 deletions src/BlazeKit.Web/Utils/UriExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
namespace BlazeKit.Web.Utils
{
public static class UriExtensions
{
public static string Param(this Uri uri, string name)
{
return Param(uri,name, () => throw new InvalidOperationException($"There is no query param with the name '{name}' in the route."));
}

public static string Param(this Uri uri, string name, string fallback)
{
return Param(uri,name, fallbackFunc: () => fallback);
}

private static string Param(Uri uri, string name, Func<string> fallbackFunc)
{
string result = string.Empty;
var queryDictionary = System.Web.HttpUtility.ParseQueryString(uri.Query);
if (queryDictionary.HasKeys() && queryDictionary.AllKeys.Contains(name))
{
result = queryDictionary[name];
} else
{
result = fallbackFunc();
}
return result;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
@using BlazeKit.Web.Components
@using System.Diagnostics
@using BlazeKit.Web.Utils
@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Authentication
@inherits PageComponentBase<SwapiPageData>
@code {

private const bool prerender = true;

protected override async Task<SwapiPageData> ServerLoadAsync()
protected override async Task<SwapiPageData> ServerLoadAsync(Uri route, HttpContext? context)
{
Debug.WriteLine($"Page Load called for '{route}'.");
var people = route.Param("people", "1");

// Modify response headers. This only has effect when SSR is used.
// If the app is statically generated, the http context will be null and the code will not be executed.
context?.Response.Headers.Add("X-BLAZEKIT-DEBUG", "enabled");

SwapiPageData result;
using (var http = new HttpClient())
{
Debug.WriteLine($"Load data from SWAPI");
http.BaseAddress = new Uri("https://swapi.dev/api/");
var response = await http.GetAsync("people/1");
var response = await http.GetAsync($"people/{people}");
response.EnsureSuccessStatusCode();
var json = System.Text.Json.JsonSerializer.Deserialize<Person>(await response.Content.ReadAsStringAsync());
Debug.WriteLine($"Got response");
Expand Down
1 change: 1 addition & 0 deletions src/BlazeKit.Website/_Imports.razor
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@
@using Humanizer;
@using BlazeKit.Website.Routes.Docs.Blazekit_CLI;
@using BlazeKit.Hydration;
@using BlazeKit.Web.Utils;

0 comments on commit 1716ca0

Please sign in to comment.