umbraco / Umbraco.Cms.Integrations

MIT License
31 stars 20 forks source link

Possibility to add custom record values in Algolia index #158

Closed piotrkrajewskicn closed 4 months ago

piotrkrajewskicn commented 5 months ago

Hi,

I believe that there is a need to add custom record values by the developers using the Algolia plugin, just as it is possible in Umbraco Examine (e.g. by subscribing to the TransformingIndexValues event).

I implemented a way to extend the default Record by the library users. As an example, let's assume we add a new content type called Article and we'd like to index an additional customField property. One can first extend the default Record class and add their custom properties, for example:

public class ArticleRecord : Record
{
    public ArticleRecord(Record record) : base(record)
    {
    }

    public required string CustomField { get; set; }
}

Then one would need to implement a generic IRecordBuilder<> interface where the generic type needs to extend PublishedContentModel so in this case that'd be Article. The method GetRecord needs to return the new extended Record type and set the extra properties values:

public class ArticleRecordBuilder : IRecordBuilder<Article>
{
    public Record GetRecord(IContent content, Record record)
    {
        return new ArticleRecord(record)
        {
            CustomField = "Custom value",
        };
    }
}

In the end the new record builder needs to be registered in services, for example:

services.AddScoped<IRecordBuilder<Article>, ArticleRecordBuilder>();

As a result after rebuilding an index, the Algolia index contains the extra field value:

image

Let me know what you think of such solution and if it can be added to the plugin in this or different form, thanks!

acoumb commented 4 months ago

Hi @piotrkrajewskicn ,

Thank you for your PR, it's fantastic to see the extension you've put in place. Before merging it, could you please, share with me a specific use case, maybe use one of the test sites for reference.

Regards, Adrian