Consolidate SoundSynth data retrieval into a single endpoint

- Added a new migration to rename and create indexes for SoundSynthPhotos.
- Updated MarechaiContext to include new composite indexes for efficient querying.
- Refactored SoundSynthsController to introduce a new GetFullAsync method that consolidates multiple data retrievals into a single call.
- Modified the View component to utilize the new consolidated endpoint, reducing the number of HTTP requests.
- Enhanced SoundSynthsService with a new method to fetch the full SoundSynth payload in one round-trip.
This commit is contained in:
2026-05-08 23:14:39 +01:00
parent a331adb485
commit 73bd8ee4ce
12 changed files with 11687 additions and 54 deletions

View File

@@ -0,0 +1,129 @@
// <auto-generated/>
#pragma warning disable CS0618
using Microsoft.Kiota.Abstractions.Extensions;
using Microsoft.Kiota.Abstractions.Serialization;
using System.Collections.Generic;
using System.IO;
using System;
namespace Marechai.ApiClient.Models
{
[global::System.CodeDom.Compiler.GeneratedCode("Kiota", "1.0.0")]
#pragma warning disable CS1591
public partial class SoundSynthFullDto : IAdditionalDataHolder, IParsable
#pragma warning restore CS1591
{
/// <summary>Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.</summary>
public IDictionary<string, object> AdditionalData { get; set; }
/// <summary>The company_logo property</summary>
public Guid? CompanyLogo { get; set; }
/// <summary>The description_html property</summary>
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER
#nullable enable
public string? DescriptionHtml { get; set; }
#nullable restore
#else
public string DescriptionHtml { get; set; }
#endif
/// <summary>The description_language_code property</summary>
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER
#nullable enable
public string? DescriptionLanguageCode { get; set; }
#nullable restore
#else
public string DescriptionLanguageCode { get; set; }
#endif
/// <summary>The description_text property</summary>
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER
#nullable enable
public string? DescriptionText { get; set; }
#nullable restore
#else
public string DescriptionText { get; set; }
#endif
/// <summary>The machines property</summary>
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER
#nullable enable
public List<global::Marechai.ApiClient.Models.MachineDto>? Machines { get; set; }
#nullable restore
#else
public List<global::Marechai.ApiClient.Models.MachineDto> Machines { get; set; }
#endif
/// <summary>The photos property</summary>
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER
#nullable enable
public List<Guid?>? Photos { get; set; }
#nullable restore
#else
public List<Guid?> Photos { get; set; }
#endif
/// <summary>The sound_synth property</summary>
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER
#nullable enable
public global::Marechai.ApiClient.Models.SoundSynthDto? SoundSynth { get; set; }
#nullable restore
#else
public global::Marechai.ApiClient.Models.SoundSynthDto SoundSynth { get; set; }
#endif
/// <summary>The videos property</summary>
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER
#nullable enable
public List<global::Marechai.ApiClient.Models.SoundSynthVideoDto>? Videos { get; set; }
#nullable restore
#else
public List<global::Marechai.ApiClient.Models.SoundSynthVideoDto> Videos { get; set; }
#endif
/// <summary>
/// Instantiates a new <see cref="global::Marechai.ApiClient.Models.SoundSynthFullDto"/> and sets the default values.
/// </summary>
public SoundSynthFullDto()
{
AdditionalData = new Dictionary<string, object>();
}
/// <summary>
/// Creates a new instance of the appropriate class based on discriminator value
/// </summary>
/// <returns>A <see cref="global::Marechai.ApiClient.Models.SoundSynthFullDto"/></returns>
/// <param name="parseNode">The parse node to use to read the discriminator value and create the object</param>
public static global::Marechai.ApiClient.Models.SoundSynthFullDto CreateFromDiscriminatorValue(IParseNode parseNode)
{
if(ReferenceEquals(parseNode, null)) throw new ArgumentNullException(nameof(parseNode));
return new global::Marechai.ApiClient.Models.SoundSynthFullDto();
}
/// <summary>
/// The deserialization information for the current model
/// </summary>
/// <returns>A IDictionary&lt;string, Action&lt;IParseNode&gt;&gt;</returns>
public virtual IDictionary<string, Action<IParseNode>> GetFieldDeserializers()
{
return new Dictionary<string, Action<IParseNode>>
{
{ "company_logo", n => { CompanyLogo = n.GetGuidValue(); } },
{ "description_html", n => { DescriptionHtml = n.GetStringValue(); } },
{ "description_language_code", n => { DescriptionLanguageCode = n.GetStringValue(); } },
{ "description_text", n => { DescriptionText = n.GetStringValue(); } },
{ "machines", n => { Machines = n.GetCollectionOfObjectValues<global::Marechai.ApiClient.Models.MachineDto>(global::Marechai.ApiClient.Models.MachineDto.CreateFromDiscriminatorValue)?.AsList(); } },
{ "photos", n => { Photos = n.GetCollectionOfPrimitiveValues<Guid?>()?.AsList(); } },
{ "sound_synth", n => { SoundSynth = n.GetObjectValue<global::Marechai.ApiClient.Models.SoundSynthDto>(global::Marechai.ApiClient.Models.SoundSynthDto.CreateFromDiscriminatorValue); } },
{ "videos", n => { Videos = n.GetCollectionOfObjectValues<global::Marechai.ApiClient.Models.SoundSynthVideoDto>(global::Marechai.ApiClient.Models.SoundSynthVideoDto.CreateFromDiscriminatorValue)?.AsList(); } },
};
}
/// <summary>
/// Serializes information the current object
/// </summary>
/// <param name="writer">Serialization writer to use to serialize this model</param>
public virtual void Serialize(ISerializationWriter writer)
{
if(ReferenceEquals(writer, null)) throw new ArgumentNullException(nameof(writer));
writer.WriteGuidValue("company_logo", CompanyLogo);
writer.WriteStringValue("description_html", DescriptionHtml);
writer.WriteStringValue("description_language_code", DescriptionLanguageCode);
writer.WriteStringValue("description_text", DescriptionText);
writer.WriteCollectionOfObjectValues<global::Marechai.ApiClient.Models.MachineDto>("machines", Machines);
writer.WriteCollectionOfPrimitiveValues<Guid?>("photos", Photos);
writer.WriteObjectValue<global::Marechai.ApiClient.Models.SoundSynthDto>("sound_synth", SoundSynth);
writer.WriteCollectionOfObjectValues<global::Marechai.ApiClient.Models.SoundSynthVideoDto>("videos", Videos);
writer.WriteAdditionalData(AdditionalData);
}
}
}
#pragma warning restore CS0618

View File

@@ -0,0 +1,108 @@
// <auto-generated/>
#pragma warning disable CS0618
using Marechai.ApiClient.Models;
using Microsoft.Kiota.Abstractions.Extensions;
using Microsoft.Kiota.Abstractions.Serialization;
using Microsoft.Kiota.Abstractions;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
using System;
namespace Marechai.ApiClient.SoundSynths.Item.Full
{
/// <summary>
/// Builds and executes requests for operations under \sound-synths\{-id}\full
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("Kiota", "1.0.0")]
public partial class FullRequestBuilder : BaseRequestBuilder
{
/// <summary>
/// Instantiates a new <see cref="global::Marechai.ApiClient.SoundSynths.Item.Full.FullRequestBuilder"/> and sets the default values.
/// </summary>
/// <param name="pathParameters">Path parameters for the request</param>
/// <param name="requestAdapter">The request adapter to use to execute the requests.</param>
public FullRequestBuilder(Dictionary<string, object> pathParameters, IRequestAdapter requestAdapter) : base(requestAdapter, "{+baseurl}/sound-synths/{%2Did}/full{?lang*}", pathParameters)
{
}
/// <summary>
/// Instantiates a new <see cref="global::Marechai.ApiClient.SoundSynths.Item.Full.FullRequestBuilder"/> and sets the default values.
/// </summary>
/// <param name="rawUrl">The raw URL to use for the request builder.</param>
/// <param name="requestAdapter">The request adapter to use to execute the requests.</param>
public FullRequestBuilder(string rawUrl, IRequestAdapter requestAdapter) : base(requestAdapter, "{+baseurl}/sound-synths/{%2Did}/full{?lang*}", rawUrl)
{
}
/// <returns>A <see cref="global::Marechai.ApiClient.Models.SoundSynthFullDto"/></returns>
/// <param name="cancellationToken">Cancellation token to use when cancelling requests</param>
/// <param name="requestConfiguration">Configuration for the request such as headers, query parameters, and middleware options.</param>
/// <exception cref="global::Marechai.ApiClient.Models.ProblemDetails">When receiving a 400 status code</exception>
/// <exception cref="global::Marechai.ApiClient.Models.ProblemDetails">When receiving a 404 status code</exception>
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER
#nullable enable
public async Task<global::Marechai.ApiClient.Models.SoundSynthFullDto?> GetAsync(Action<RequestConfiguration<global::Marechai.ApiClient.SoundSynths.Item.Full.FullRequestBuilder.FullRequestBuilderGetQueryParameters>>? requestConfiguration = default, CancellationToken cancellationToken = default)
{
#nullable restore
#else
public async Task<global::Marechai.ApiClient.Models.SoundSynthFullDto> GetAsync(Action<RequestConfiguration<global::Marechai.ApiClient.SoundSynths.Item.Full.FullRequestBuilder.FullRequestBuilderGetQueryParameters>> requestConfiguration = default, CancellationToken cancellationToken = default)
{
#endif
var requestInfo = ToGetRequestInformation(requestConfiguration);
var errorMapping = new Dictionary<string, ParsableFactory<IParsable>>
{
{ "400", global::Marechai.ApiClient.Models.ProblemDetails.CreateFromDiscriminatorValue },
{ "404", global::Marechai.ApiClient.Models.ProblemDetails.CreateFromDiscriminatorValue },
};
return await RequestAdapter.SendAsync<global::Marechai.ApiClient.Models.SoundSynthFullDto>(requestInfo, global::Marechai.ApiClient.Models.SoundSynthFullDto.CreateFromDiscriminatorValue, errorMapping, cancellationToken).ConfigureAwait(false);
}
/// <returns>A <see cref="RequestInformation"/></returns>
/// <param name="requestConfiguration">Configuration for the request such as headers, query parameters, and middleware options.</param>
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER
#nullable enable
public RequestInformation ToGetRequestInformation(Action<RequestConfiguration<global::Marechai.ApiClient.SoundSynths.Item.Full.FullRequestBuilder.FullRequestBuilderGetQueryParameters>>? requestConfiguration = default)
{
#nullable restore
#else
public RequestInformation ToGetRequestInformation(Action<RequestConfiguration<global::Marechai.ApiClient.SoundSynths.Item.Full.FullRequestBuilder.FullRequestBuilderGetQueryParameters>> requestConfiguration = default)
{
#endif
var requestInfo = new RequestInformation(Method.GET, UrlTemplate, PathParameters);
requestInfo.Configure(requestConfiguration);
requestInfo.Headers.TryAdd("Accept", "application/json, text/plain;q=0.9");
return requestInfo;
}
/// <summary>
/// Returns a request builder with the provided arbitrary URL. Using this method means any other path or query parameters are ignored.
/// </summary>
/// <returns>A <see cref="global::Marechai.ApiClient.SoundSynths.Item.Full.FullRequestBuilder"/></returns>
/// <param name="rawUrl">The raw URL to use for the request builder.</param>
public global::Marechai.ApiClient.SoundSynths.Item.Full.FullRequestBuilder WithUrl(string rawUrl)
{
return new global::Marechai.ApiClient.SoundSynths.Item.Full.FullRequestBuilder(rawUrl, RequestAdapter);
}
[global::System.CodeDom.Compiler.GeneratedCode("Kiota", "1.0.0")]
#pragma warning disable CS1591
public partial class FullRequestBuilderGetQueryParameters
#pragma warning restore CS1591
{
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER
#nullable enable
[QueryParameter("lang")]
public string? Lang { get; set; }
#nullable restore
#else
[QueryParameter("lang")]
public string Lang { get; set; }
#endif
}
/// <summary>
/// Configuration for the request such as headers, query parameters, and middleware options.
/// </summary>
[Obsolete("This class is deprecated. Please use the generic RequestConfiguration class generated by the generator.")]
[global::System.CodeDom.Compiler.GeneratedCode("Kiota", "1.0.0")]
public partial class FullRequestBuilderGetRequestConfiguration : RequestConfiguration<global::Marechai.ApiClient.SoundSynths.Item.Full.FullRequestBuilder.FullRequestBuilderGetQueryParameters>
{
}
}
}
#pragma warning restore CS0618

View File

@@ -3,6 +3,7 @@
using Marechai.ApiClient.Models;
using Marechai.ApiClient.SoundSynths.Item.Description;
using Marechai.ApiClient.SoundSynths.Item.Descriptions;
using Marechai.ApiClient.SoundSynths.Item.Full;
using Marechai.ApiClient.SoundSynths.Item.Machines;
using Marechai.ApiClient.SoundSynths.Item.Photos;
using Marechai.ApiClient.SoundSynths.Item.Videos;
@@ -32,6 +33,11 @@ namespace Marechai.ApiClient.SoundSynths.Item
{
get => new global::Marechai.ApiClient.SoundSynths.Item.Descriptions.DescriptionsRequestBuilder(PathParameters, RequestAdapter);
}
/// <summary>The full property</summary>
public global::Marechai.ApiClient.SoundSynths.Item.Full.FullRequestBuilder Full
{
get => new global::Marechai.ApiClient.SoundSynths.Item.Full.FullRequestBuilder(PathParameters, RequestAdapter);
}
/// <summary>The machines property</summary>
public global::Marechai.ApiClient.SoundSynths.Item.Machines.MachinesRequestBuilder Machines
{

View File

@@ -1,5 +1,5 @@
{
"descriptionHash": "18CCAA5AB1EB61E4C6AD4D508A4A990449F492E780F84384BD5721DDEC3F4EB07301E868DC18FB336E887B60816D3EA00E73CD801CF35979D08DE5A788482FC7",
"descriptionHash": "389F8BA108D981456765FE8C3A9288855C430D007CA1DEA039290889224411A5630995CA2A8D9CCFC43727EC38FA727627E08ACB6E9FEB19709049107313B727",
"descriptionLocation": "../../../../../tmp/openapi.json",
"lockFileVersion": "1.0.0",
"kiotaVersion": "1.31.1",

View File

@@ -0,0 +1,98 @@
/******************************************************************************
// MARECHAI: Master repository of computing history artifacts information
// ----------------------------------------------------------------------------
//
// Author(s) : Natalia Portillo <claunia@claunia.com>
//
// --[ License ] --------------------------------------------------------------
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------
// Copyright © 2003-2026 Natalia Portillo
*******************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
namespace Marechai.Data.Dtos;
/// <summary>
/// Consolidated payload for the public /soundsynth/{Id} view page. Replaces 5 sequential
/// HTTP round-trips (head + machines + description + photos + videos) with a single
/// response. The head + company name + company logo are pulled in one projected query
/// (logo via inline correlated subquery so it costs zero extra DB round-trips); the
/// description language fallback is collapsed into a single ordered query; the child
/// collections are fetched in parallel using independent <see cref="Marechai.Database.Models.MarechaiContext"/>
/// instances from <c>IDbContextFactory</c> (DbContext is not thread-safe; sharing the
/// request-scoped context across parallel branches throws <c>InvalidOperationException</c>).
/// </summary>
public class SoundSynthFullDto
{
// [Required] is needed in addition to the non-nullable type so the generated
// OpenAPI schema is a plain $ref instead of `oneOf:[null, $ref]`. With the
// oneOf-with-null shape Kiota generates a "composed type wrapper" that
// requires a discriminator field that doesn't exist in the JSON, leaving the
// inner DTO un-populated. See pattern in BookFullDto.Book, GpuFullDto.Gpu and
// ProcessorFullDto.Processor.
[JsonPropertyName("sound_synth")]
[Required]
public SoundSynthDto SoundSynth { get; set; }
/// <summary>
/// Asset GUID of the company logo to display next to the sound synth header. Picked
/// from the company's logos with the introduced-year preference applied server-side
/// (logos with <c>Year &gt;= introducedYear</c> sort first, then ascending by year).
/// Null when the synth has no company or the company has no logos.
/// </summary>
[JsonPropertyName("company_logo")]
public Guid? CompanyLogo { get; set; }
/// <summary>
/// HTML-rendered description in the requested language (with English fallback applied
/// server-side via a single ordered query). Null at runtime when the synth has no
/// description in either the requested language or English.
/// </summary>
[JsonPropertyName("description_html")]
public string? DescriptionHtml { get; set; }
/// <summary>
/// Plain-text (markdown source) description in the requested language. Mirrors
/// <see cref="DescriptionHtml"/> for callers that prefer raw markdown over rendered
/// HTML. Null when no description was found.
/// </summary>
[JsonPropertyName("description_text")]
public string? DescriptionText { get; set; }
/// <summary>
/// Language code of the description that was actually returned (the requested language
/// or "eng" if the fallback fired). Null when no description was found.
/// </summary>
[JsonPropertyName("description_language_code")]
public string? DescriptionLanguageCode { get; set; }
[JsonPropertyName("machines")]
[Required]
public List<MachineDto> Machines { get; set; } = new();
[JsonPropertyName("photos")]
[Required]
public List<Guid> Photos { get; set; } = new();
[JsonPropertyName("videos")]
[Required]
public List<SoundSynthVideoDto> Videos { get; set; } = new();
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,37 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Marechai.Database.Migrations
{
/// <inheritdoc />
public partial class AddSoundSynthPhotosSoundSynthIdIndex : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameIndex(
name: "IX_SoundSynthPhotos_SoundSynthId",
table: "SoundSynthPhotos",
newName: "idx_sound_synth_photos_sound_synth");
migrationBuilder.CreateIndex(
name: "idx_sound_synth_photos_sound_synth_created",
table: "SoundSynthPhotos",
columns: new[] { "SoundSynthId", "CreatedOn", "Id" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "idx_sound_synth_photos_sound_synth_created",
table: "SoundSynthPhotos");
migrationBuilder.RenameIndex(
name: "idx_sound_synth_photos_sound_synth",
table: "SoundSynthPhotos",
newName: "IX_SoundSynthPhotos_SoundSynthId");
}
}
}

View File

@@ -8047,7 +8047,8 @@ namespace Marechai.Database.Migrations
b.HasIndex("SoftwareUsed");
b.HasIndex("SoundSynthId");
b.HasIndex("SoundSynthId")
.HasDatabaseName("idx_sound_synth_photos_sound_synth");
b.HasIndex("SubjectDistanceRange");
@@ -8059,6 +8060,9 @@ namespace Marechai.Database.Migrations
b.HasIndex("WhiteBalance");
b.HasIndex("SoundSynthId", "CreatedOn", "Id")
.HasDatabaseName("idx_sound_synth_photos_sound_synth_created");
b.ToTable("SoundSynthPhotos");
});

View File

@@ -1344,6 +1344,15 @@ public class MarechaiContext : IdentityDbContext<ApplicationUser, ApplicationRol
entity.HasIndex(e => e.WhiteBalance);
// FK index for /sound-synths/{id}/photos lookups (matches the
// MachinePhoto/GpuPhoto/ProcessorPhoto pattern: this FK was missing
// among the 30+ EXIF indexes). Composite (SoundSynthId, CreatedOn,
// Id) backs the OrderBy(CreatedOn).ThenBy(Id) sort.
entity.HasIndex(e => e.SoundSynthId).HasDatabaseName("idx_sound_synth_photos_sound_synth");
entity.HasIndex(e => new { e.SoundSynthId, e.CreatedOn, e.Id })
.HasDatabaseName("idx_sound_synth_photos_sound_synth_created");
entity.HasOne(d => d.SoundSynth).WithMany(p => p.Photos).OnDelete(DeleteBehavior.Cascade);
entity.HasOne(d => d.User).WithMany().OnDelete(DeleteBehavior.SetNull);

View File

@@ -41,7 +41,9 @@ namespace Marechai.Server.Controllers;
[Route("/sound-synths")]
[ApiController]
public class SoundSynthsController(MarechaiContext context) : ControllerBase
public class SoundSynthsController(
MarechaiContext context,
IDbContextFactory<MarechaiContext> dbFactory) : ControllerBase
{
[HttpGet]
[AllowAnonymous]
@@ -122,7 +124,8 @@ public class SoundSynthsController(MarechaiContext context) : ControllerBase
[AllowAnonymous]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public Task<SoundSynthDto> GetAsync(int id) => context.SoundSynths.Where(s => s.Id == id)
public Task<SoundSynthDto> GetAsync(int id) => context.SoundSynths.AsNoTracking()
.Where(s => s.Id == id)
.Select(s => new SoundSynthDto
{
Id = s.Id,
@@ -141,6 +144,160 @@ public class SoundSynthsController(MarechaiContext context) : ControllerBase
})
.FirstOrDefaultAsync();
/// <summary>
/// Consolidated payload for the public /soundsynth/{Id} view page. Replaces five
/// sequential HTTP round-trips (head + machines + description + photos + videos)
/// with a single response. The head + company name + company logo are projected in
/// one query (logo is an inline correlated subquery so it costs zero extra DB
/// round-trips); the description language fallback is collapsed into a single
/// ordered query; the three child collections are fetched in parallel using
/// independent <see cref="MarechaiContext"/> instances from <c>IDbContextFactory</c>
/// (DbContext is not thread-safe; sharing the request-scoped context across parallel
/// branches throws <c>InvalidOperationException</c>).
/// </summary>
[HttpGet("{id:int}/full")]
[AllowAnonymous]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<SoundSynthFullDto>> GetFullAsync(int id, [FromQuery] string lang = "eng")
{
// Head + description + the three child collections only depend on `id`
// (from the URL) and not on any value projected by the head query, so we
// fire all FIVE queries in parallel using independent DbContext instances
// from the factory. Compared to running head first and then the children
// in parallel, this saves one full ~180 ms RTT in the common case. The
// company-logo lookup is folded into the head query as an inline
// correlated subquery so it adds zero extra DB round-trips.
await using var headCtx = await dbFactory.CreateDbContextAsync();
await using var descriptionCtx = await dbFactory.CreateDbContextAsync();
await using var machinesCtx = await dbFactory.CreateDbContextAsync();
await using var photosCtx = await dbFactory.CreateDbContextAsync();
await using var videosCtx = await dbFactory.CreateDbContextAsync();
// Head + company name + company logo in a single projected join.
// The CompanyLogo lookup uses an inline correlated subquery ordered
// such that logos issued on or after the synth's introduction year sort
// first (key 0), then any other logo by ascending year. Returns null
// when the synth does not exist; we surface that as 404 below.
var headTask = headCtx.SoundSynths.AsNoTracking()
.Where(s => s.Id == id)
.Select(s => new
{
s.Id,
s.Name,
s.CompanyId,
CompanyName = s.Company.Name,
s.ModelCode,
s.Introduced,
s.IntroducedPrecision,
s.Voices,
s.Frequency,
s.Depth,
s.SquareWave,
s.WhiteNoise,
s.Type,
CompanyLogo = s.Company.Logos
.OrderBy(l => s.Introduced.HasValue && l.Year >= s.Introduced.Value.Year
? 0
: 1)
.ThenBy(l => l.Year)
.Select(l => (Guid?)l.Guid)
.FirstOrDefault()
})
.FirstOrDefaultAsync();
// Description: collapse the original two-step lookup (try requested
// lang, then English fallback) into a single ordered query. Matches
// for the requested language sort first (key 0); English fallback is
// key 1; FirstOrDefaultAsync returns the preferred row.
var descriptionTask = descriptionCtx.SoundSynthDescriptions.AsNoTracking()
.Where(d => d.SoundSynthId == id && (d.LanguageCode == lang || d.LanguageCode == "eng"))
.OrderBy(d => d.LanguageCode == lang ? 0 : 1)
.Select(d => new { d.Html, d.Text, d.LanguageCode })
.FirstOrDefaultAsync();
// Mirrors GetMachinesBySoundSynthAsync.
Task<List<MachineDto>> machinesTask = machinesCtx.SoundByMachine.AsNoTracking()
.Where(s => s.SoundSynthId == id)
.Select(s => s.Machine)
.OrderBy(m => m.Company.Name)
.ThenBy(m => m.Name)
.Select(m => new MachineDto
{
Id = m.Id,
Company = m.Company.Name,
CompanyId = m.Company.Id,
Name = m.Name,
Model = m.Model,
Introduced = m.Introduced,
IntroducedPrecision = m.IntroducedPrecision,
Type = m.Type,
FamilyId = m.FamilyId
})
.ToListAsync();
// Mirrors SoundSynthPhotosController.GetGuidsBySoundSynthAsync.
Task<List<Guid>> photosTask = photosCtx.SoundSynthPhotos.AsNoTracking()
.Where(p => p.SoundSynthId == id)
.OrderBy(p => p.CreatedOn)
.ThenBy(p => p.Id)
.Select(p => p.Id)
.ToListAsync();
// Mirrors SoundSynthVideosController.GetVideosBySoundSynthAsync.
Task<List<SoundSynthVideoDto>> videosTask = videosCtx.SoundSynthVideos.AsNoTracking()
.Where(v => v.SoundSynthId == id)
.OrderBy(v => v.Title)
.Select(v => new SoundSynthVideoDto
{
Id = v.Id,
SoundSynthId = v.SoundSynthId,
SoundSynthName = v.SoundSynth.Name,
Provider = v.Provider,
VideoId = v.VideoId,
Title = v.Title
})
.ToListAsync();
await Task.WhenAll(headTask, descriptionTask, machinesTask, photosTask, videosTask);
var head = headTask.Result;
if(head is null) return NotFound();
var synth = new SoundSynthDto
{
Id = head.Id,
Name = head.Name,
CompanyId = head.CompanyId,
CompanyName = head.CompanyName,
ModelCode = head.ModelCode,
Introduced = head.Introduced,
IntroducedPrecision = head.IntroducedPrecision,
Voices = head.Voices,
Frequency = head.Frequency,
Depth = head.Depth,
SquareWave = head.SquareWave,
WhiteNoise = head.WhiteNoise,
Type = head.Type
};
var description = descriptionTask.Result;
return new SoundSynthFullDto
{
SoundSynth = synth,
CompanyLogo = head.CompanyLogo,
DescriptionHtml = description?.Html,
DescriptionText = description?.Text,
DescriptionLanguageCode = description?.LanguageCode,
Machines = machinesTask.Result,
Photos = photosTask.Result,
Videos = videosTask.Result
};
}
[HttpPut("{id:int}")]
[Authorize(Roles = "Admin,UberAdmin")]
[ProducesResponseType(StatusCodes.Status200OK)]
@@ -257,13 +414,14 @@ public class SoundSynthsController(MarechaiContext context) : ControllerBase
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<string> GetDescriptionTextAsync(int id, [FromQuery] string lang = "eng")
{
SoundSynthDescription description =
await context.SoundSynthDescriptions.FirstOrDefaultAsync(d => d.SoundSynthId == id && d.LanguageCode == lang);
// Fallback to English if requested language not found
if(description is null && lang != "eng")
description = await context.SoundSynthDescriptions.FirstOrDefaultAsync(d => d.SoundSynthId == id &&
d.LanguageCode == "eng");
// Single ordered query: requested-language matches sort first (key 0),
// English fallback is key 1. Saves one ~RTT vs the original two-step
// lookup when the fallback fires.
var description = await context.SoundSynthDescriptions.AsNoTracking()
.Where(d => d.SoundSynthId == id && (d.LanguageCode == lang || d.LanguageCode == "eng"))
.OrderBy(d => d.LanguageCode == lang ? 0 : 1)
.Select(d => new { d.Html, d.Text })
.FirstOrDefaultAsync();
return description?.Html ?? description?.Text;
}
@@ -289,38 +447,23 @@ public class SoundSynthsController(MarechaiContext context) : ControllerBase
[AllowAnonymous]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<SoundSynthDescriptionDto> GetDescriptionAsync(int id, [FromQuery] string lang = "eng")
{
SoundSynthDescriptionDto description = await context.SoundSynthDescriptions
.Where(d => d.SoundSynthId == id && d.LanguageCode == lang)
.Select(d => new SoundSynthDescriptionDto
{
Id = d.Id,
SoundSynthId = d.SoundSynthId,
Html = d.Html,
Markdown = d.Text,
LanguageCode = d.LanguageCode,
Language = d.Language.ReferenceName
})
.FirstOrDefaultAsync();
// Fallback to English if requested language not found
if(description is null && lang != "eng")
description = await context.SoundSynthDescriptions
.Where(d => d.SoundSynthId == id && d.LanguageCode == "eng")
.Select(d => new SoundSynthDescriptionDto
{
Id = d.Id,
SoundSynthId = d.SoundSynthId,
Html = d.Html,
Markdown = d.Text,
LanguageCode = d.LanguageCode,
Language = d.Language.ReferenceName
})
.FirstOrDefaultAsync();
return description;
}
public Task<SoundSynthDescriptionDto> GetDescriptionAsync(int id, [FromQuery] string lang = "eng") =>
// Single ordered query: requested-language matches sort first (key 0),
// English fallback is key 1. Saves one ~RTT vs the original two-step
// lookup when the fallback fires.
context.SoundSynthDescriptions.AsNoTracking()
.Where(d => d.SoundSynthId == id && (d.LanguageCode == lang || d.LanguageCode == "eng"))
.OrderBy(d => d.LanguageCode == lang ? 0 : 1)
.Select(d => new SoundSynthDescriptionDto
{
Id = d.Id,
SoundSynthId = d.SoundSynthId,
Html = d.Html,
Markdown = d.Text,
LanguageCode = d.LanguageCode,
Language = d.Language.ReferenceName
})
.FirstOrDefaultAsync();
[HttpPost("{id:int}/description")]
[Authorize(Roles = "Admin,UberAdmin")]

View File

@@ -104,29 +104,42 @@ public partial class View
return;
}
_synth = await Service.GetByIdAsync(Id);
// ── Phase 1+3 retrofit ────────────────────────────────────────────────
// One consolidated HTTP round-trip via /sound-synths/{Id}/full (head
// projection + company logo via inline subquery + description with
// single-query language fallback + machines + photos + videos), all
// executed in parallel server-side on independent DbContext instances.
// Replaces the original 5 sequential GetByIdAsync /
// GetMachinesBySoundSynthAsync / GetDescriptionTextAsync /
// GetGuidsBySoundSynthAsync / GetVideosBySoundSynthAsync calls.
SoundSynthFullDto full = await Service.GetFullAsync(Id);
if(_synth is null)
if(full?.SoundSynth is null)
{
_synth = null;
_loaded = true;
StateHasChanged();
return;
}
_synth = full.SoundSynth;
_displayName = _synth.Name == "DB_SOFTWARE" ? L["Software"] : _synth.Name;
List<MachineDto> machines = await Service.GetMachinesBySoundSynthAsync(Id);
_computers = machines.Where(m => m.Type == (int)MachineType.Computer).ToList();
_consoles = machines.Where(m => m.Type == (int)MachineType.Console).ToList();
// Photos arrive as List<Guid?>? (Kiota emits nullable element type even
// for non-nullable server collections). Materialise into the existing
// List<Guid> field shape that the .razor view expects.
_photos = full.Photos?.Where(g => g.HasValue).Select(g => g!.Value).ToList() ?? [];
_videos = full.Videos ?? [];
_description = full.DescriptionHtml ?? full.DescriptionText;
List<MachineDto> machines = full.Machines ?? [];
_computers = machines.Where(m => m.Type == (int)MachineType.Computer).ToList();
_consoles = machines.Where(m => m.Type == (int)MachineType.Console).ToList();
_smartphones = machines.Where(m => m.Type == (int)MachineType.Smartphone).ToList();
_description = await Service.GetDescriptionTextAsync(Id);
_photos = await SoundSynthPhotosService.GetGuidsBySoundSynthAsync(Id);
_videos = await Service.GetVideosBySoundSynthAsync(Id);
// Insert the Machines tab between Specifications and Media when the
// synth has any attached computers/consoles/smartphones, so
// _activeTabIndex resolves "machines" correctly on first paint after a

View File

@@ -66,6 +66,29 @@ public class SoundSynthsService(Marechai.ApiClient.Client client)
}
}
/// <summary>
/// Fetches the consolidated /soundsynth/{Id} payload (head + company logo + description
/// + machines + photos + videos) in a single HTTP round-trip. Replaces the original
/// 5-call sequence (GetByIdAsync + GetMachinesBySoundSynthAsync + GetDescriptionTextAsync
/// + SoundSynthPhotosService.GetGuidsBySoundSynthAsync + GetVideosBySoundSynthAsync).
/// Returns <c>null</c> on any transport-level failure or 404; the caller should treat
/// null the same way it treated <c>GetByIdAsync</c> returning null.
/// </summary>
public async Task<SoundSynthFullDto> GetFullAsync(int id, string lang = "eng")
{
try
{
return await client.SoundSynths[id].Full.GetAsync(rc =>
{
if(!string.IsNullOrEmpty(lang)) rc.QueryParameters.Lang = lang;
});
}
catch
{
return null;
}
}
public async Task<(long? id, string error)> CreateAsync(SoundSynthDto dto)
{
try