1729013949
2024-10-15 15:41:00
こんにちは、みんな、
このブログは、コンテンツ配信 API を使用してヘッドレスのアーキテクチャを開始または構築したい人に役立ちます。
ヘッドレス CMS 12 に移行したとき、私の最初の疑問は、フロントエンドからコンテンツがどのように取得されるかでした (フロントエンド用の直接 API があることはわかっています)。それは、それらのページまたはブロックの JSON を構築することについてでした。
そこで、私のコード体験を段階的に共有していきます (ここではページの例を取り上げていますが、ブロックに対しても同じことができます)。
- 通常のページタイプを作成します。
- さて、コンパイラはどのページを実行する必要があるかをどのようにして知るのでしょうか。通常のアーキテクチャで慣れているため、ビューからコントローラに直接呼び出しているわけではないので、そのためにApiFiltersを作成します(呼び出しごとにすべて実行されます)。
- この _services.AddSingleton のように、その API フィルターをシングルトンとして登録します
(); - フィルター内で、現在のリクエストがタイプと一致するかどうかを確認する必要があります。一致しない場合は、何もせずに戻ります。
- タイプが一致する場合は、コンテンツエリアを JSON 結果に追加するカスタム コードを作成する必要があります。そのために、JSON で渡されるモデルのフィルタリングとバインドを行うメソッドを作成します。
-
public void AddContentAreaItemsToContentApiModel(string key, ContentArea contentArea, ContentApiModel contentApiModel) { var items = new Dictionary(); if (contentArea == null || contentArea.FilteredItems == null) { contentApiModel.Properties.Add(key, items); return; } var Filtereditems = contentArea.FilteredItems; var index = 0; //Will be appended to the item name in the contentApiModel to prevent duplicate keys in case we have multiples of the same block type foreach (var contentAreaItem in Filtereditems) { _contentLoader.TryGet (contentAreaItem.ContentLink, out var content); if (content == null) continue; switch (content) { // all blocks and pages that will be there in the content area create a case for it like this case PageType x: { items.Add(nameof(PageType ) + "_" + index, _commerceViewModelBuilder.GetPageDetails(x)); index++; break; } default: { index++; break; } } } contentApiModel.Properties.Add(key, items); } - このフィルターは、JSON 結果となるキーと値のペアを作成します。
- GetPageDetails -> そのタイプを受け入れ、追加するモデルを作成するメソッド。
- この _services.AddSingleton のように、その API フィルターをシングルトンとして登録します
- このメソッドをページ タイプ フィルターに追加し、その中でコンテンツ領域を呼び出してすべてのものをフィルターします。
public class PageApiModelFilter : ContentApiModelFilter{ public override void Filter(ContentApiModel contentApiModel, ConverterContext converterContext) { try { if (!_contentLoader.TryGet(converterContext.ContentReference, out ProductCollectionPage productCollectionPage) || productCollectionPage is not ProductCollectionPage) { return; } AddContentAreaItemsToContentApiModel(nameof(productCollectionPage.TopContentArea), productCollectionPage.TopContentArea, contentApiModel); AddContentAreaItemsToContentApiModel(nameof(productCollectionPage.MainContentArea), productCollectionPage.MainContentArea, contentApiModel); AddContentAreaItemsToContentApiModel(nameof(productCollectionPage.BottomContentArea), productCollectionPage.BottomContentArea, contentApiModel); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
4. これで、ID またはその他の手段を使用してフロントエンドから API を呼び出すことができ、シリアル化されたすべてのデータが JSON で取得されます。
シリアル化の前後に余分なデータを削除したい場合は、私の他のブログを参照してください。ここにリンクがあります。 https://world.optimizely.com/blogs/puneetgarg/dates/2024/9/remove-unwanted-properties-for-headless-implementation-using-content-delivery-api-/
お役に立てば幸いです!
ありがとう
2024 年 10 月 15 日
#コンテンツ配信 #API #を使用したヘッドレス