Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

1.2 KB
Raw Blame
using Grand.SharedKernel.Attributes;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi;
using System.Reflection;

namespace Grand.Module.Api.Infrastructure.Transformers;

public class IgnoreFieldSchemaTransformer : IOpenApiSchemaTransformer
{
    public Task TransformAsync(OpenApiSchema schema, OpenApiSchemaTransformerContext context, CancellationToken cancellationToken)
    {

        var type = context.JsonTypeInfo.Type;
        if (type == null || schema.Properties == null || !schema.Properties.Any()) return Task.CompletedTask;
        
        var excludedPropertyNames = type
            .GetProperties()
            .Where(
                t => t.GetCustomAttribute<IgnoreApiAttribute>() != null
            ).Select(d => d.Name).ToList();

        if (!excludedPropertyNames.Any()) return Task.CompletedTask;

        var excludedSchemaPropertyKey = schema.Properties
            .Where(
                ap => excludedPropertyNames.Any(
                    pn => pn.Equals(ap.Key, StringComparison.InvariantCultureIgnoreCase)
                )
            ).Select(ap => ap.Key).ToList();

        foreach (var propertyToExclude in excludedSchemaPropertyKey) schema.Properties.Remove(propertyToExclude);

        return Task.CompletedTask;
    }
}