Skip to content

Commit

Permalink
Add a RatingsService and use it from the frontend
Browse files Browse the repository at this point in the history
  • Loading branch information
Pilchie committed Nov 1, 2023
1 parent 85a66a8 commit 4f01310
Show file tree
Hide file tree
Showing 9 changed files with 137 additions and 3 deletions.
17 changes: 17 additions & 0 deletions samples/eShopLite/ApiGateway/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@
"Transforms": [
{ "PathRemovePrefix": "/basket" }
]
},
"rating": {
"ClusterId": "rating",
"Match": {
"Path": "/rating/{**catch-all}"
},
"Transforms": [
{ "PathRemovePrefix": "/rating" }
]
}
},
"Clusters": {
Expand All @@ -43,6 +52,14 @@
"Health": "http://basketservice/readiness"
}
}
},
"rating": {
"Destinations": {
"rating": {
"Address": "http://ratingservice",
"Health": "http://ratingservice/readiness"
}
}
}
}
}
Expand Down
1 change: 1 addition & 0 deletions samples/eShopLite/AppHost/AppHost.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
<ProjectReference Include="..\CatalogService\CatalogService.csproj" />
<ProjectReference Include="..\MyFrontend\MyFrontend.csproj" />
<ProjectReference Include="..\OrderProcessor\OrderProcessor.csproj" />
<ProjectReference Include="..\RatingsService\RatingsService.csproj" />
</ItemGroup>

</Project>
13 changes: 10 additions & 3 deletions samples/eShopLite/AppHost/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,18 @@

builder.AddAzureProvisioning();

var catalogdb = builder.AddAzureCosmosDB("cosmosdb").AddDatabase("catalogdb");
var cosmosdb = builder.AddAzureCosmosDB("cosmosdb");
var catalogdb = cosmosdb.AddDatabase("catalogdb");
var ratingsdb = cosmosdb.AddDatabase("ratingsdb");

var basketCache = builder.AddRedisContainer("basketCache");

var catalogService = builder.AddProject<Projects.CatalogService>("catalogservice")
.WithReference(catalogdb);

var ratingsService = builder.AddProject<Projects.RatingsService>("ratingsservice")
.WithReference(ratingsdb);

var messaging = builder.AddRabbitMQContainer("messaging");

var basketService = builder.AddProject<Projects.BasketService>("basketservice")
Expand All @@ -17,15 +22,17 @@

builder.AddProject<Projects.MyFrontend>("frontend")
.WithReference(basketService)
.WithReference(catalogService.GetEndpoint("http"));
.WithReference(catalogService.GetEndpoint("http"))
.WithReference(ratingsService.GetEndpoint("http"));

builder.AddProject<Projects.OrderProcessor>("orderprocessor")
.WithReference(messaging)
.WithLaunchProfile("OrderProcessor");

builder.AddProject<Projects.ApiGateway>("apigateway")
.WithReference(basketService)
.WithReference(catalogService);
.WithReference(catalogService)
.WithReference(ratingsService);

builder.AddProject<Projects.CatalogDb>("catalogdbapp")
.WithReference(catalogdb);
Expand Down
15 changes: 15 additions & 0 deletions samples/eShopLite/MyFrontend/Components/Pages/Home.razor
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
@attribute [StreamRendering(true)]

@inject CatalogServiceClient CatalogService
@inject RatingServiceClient RatingService

<PageTitle>eShopLite Product Catalog</PageTitle>

Expand Down Expand Up @@ -34,6 +35,7 @@
{
<AddToCart Item="item" />
}
<p class="item-rating pointer-events-none">@ratings[item.Id]</p>
</div>
</div>
</div>
Expand Down Expand Up @@ -65,6 +67,7 @@
bool basketIsAvailable;
Catalog? catalog;
PaginationInfo paginationInfo = new(FirstId: 0, NextId: 0, HasPreviousPage: false, HasNextPage: false);
Dictionary<int, string> ratings = new();

[SupplyParameterFromQuery]
public int? Before { get; set; }
Expand All @@ -81,6 +84,18 @@
return;
}

var idsAndTasks = new List<(int id, Task<string> task)>();
foreach (var item in catalog.Data)
{
idsAndTasks.Add((item.Id, RatingService.GetRatingAsync(item.Id)));
}
await Task.WhenAll(idsAndTasks.Select(i => i.task));

foreach (var (id, task) in idsAndTasks)
{
ratings[id] = task.Result;
}

paginationInfo = new PaginationInfo(catalog.FirstId, catalog.NextId, catalog.FirstId > 1, !catalog.IsLastPage);
}

Expand Down
2 changes: 2 additions & 0 deletions samples/eShopLite/MyFrontend/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
builder.Services.AddHttpForwarderWithServiceDiscovery();

builder.Services.AddHttpClient<CatalogServiceClient>(c => c.BaseAddress = new("http://catalogservice"));
//builder.Services.AddHttpClient<RatingServiceClient>(c => c.BaseAddress = new("http://ratingservice"));
builder.Services.AddHttpClient<RatingServiceClient>(c => c.BaseAddress = new("http://localhost:5419"));

builder.Services.AddSingleton<BasketServiceClient>()
.AddGrpcClient<Basket.BasketClient>(o => o.Address = new("http://basketservice"));
Expand Down
14 changes: 14 additions & 0 deletions samples/eShopLite/MyFrontend/Services/RatingServiceClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;

namespace MyFrontend.Services;

public class RatingServiceClient(HttpClient client)
{
public Task<string> GetRatingAsync(int productId)
{
return client.GetStringAsync($"averagerating/{productId.ToString(CultureInfo.InvariantCulture)}");
}
}
49 changes: 49 additions & 0 deletions samples/eShopLite/RatingsService/Program.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,36 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Cosmos.Linq;
using RatingsService;

var builder = WebApplication.CreateBuilder(args);

builder.AddServiceDefaults();

builder.AddAzureCosmosDB("ratingsdb");

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddProblemDetails();
builder.Services.AddSwaggerGen();

var app = builder.Build();

var cc = app.Services.GetRequiredService<CosmosClient>();
var dbr = await cc.CreateDatabaseIfNotExistsAsync("ratingsdb");
var cr = await dbr.Database.CreateContainerIfNotExistsAsync("ratings", "/ProductId");
var ir = await cr.Container.UpsertItemAsync(
new Rating
{
RatingId = "0",
ProductId = "1",
RatingValue = 5,
User = "kevinpi",
Review = "Great product!"
});

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
Expand All @@ -19,6 +41,33 @@
app.UseExceptionHandler();
}

app.MapGet("averagerating/{productId}", async (string productId, CosmosClient cosmosClient) =>
{
var container = cosmosClient.GetContainer("ratingsdb", "ratings");
var feed = container.GetItemLinqQueryable<Rating>(true)
.Where(r => r.ProductId == productId)
.ToFeedIterator();
var ratings = new List<Rating>();
var sum = 0f;
var count = 0;
while (feed.HasMoreResults)
{
foreach (var r in await feed.ReadNextAsync())
{
sum += r.RatingValue;
count++;
}
}
var result = count > 0
? (sum / count).ToString("0.00", CultureInfo.InvariantCulture) + " / 5"
: "no ratings";
return result;
});

app.MapDefaultEndpoints();

app.Run();
28 changes: 28 additions & 0 deletions samples/eShopLite/RatingsService/Rating.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;

namespace RatingsService;

public class Rating
{
/// <summary>A unique id for this rating.</summary>
[Required, JsonProperty("id")]
public string RatingId { get; set; } = "";

/// <summary>The ProductId that this rating is for.</summary>
[Required]
public string ProductId { get; set; } = "";

/// <summary>The value of this rating (from 1 to 5).</summary>
[Range(1, 5)]
public int RatingValue { get; set; }

/// <summary>The user who gave this rating (optional).</summary>
public string? User { get; set; }

/// <summary>The text of the review (optional).</summary>
public string? Review { get; set; }
}
1 change: 1 addition & 0 deletions samples/eShopLite/RatingsService/RatingsService.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\src\Components\Aspire.Microsoft.Azure.Cosmos\Aspire.Microsoft.Azure.Cosmos.csproj" />
<ProjectReference Include="..\ServiceDefaults\ServiceDefaults.csproj" />
</ItemGroup>

Expand Down

0 comments on commit 4f01310

Please sign in to comment.