Burgyn / MMLib.SwaggerForOcelot

This repo contains swagger extension for ocelot.
MIT License
353 stars 94 forks source link

Problem with Paths in Swagger JSON: Service Name Prefix Missing #312

Open rabdulatif opened 1 month ago

rabdulatif commented 1 month ago

There is a problem with the paths section in the generated Swagger JSON. The paths currently do not include the appropriate service name prefix, causing potential issues with routing and API documentation, especially in microservice-based environments like Ocelot.

Each path in the Swagger JSON should be prefixed with the serviceName associated with the microservice. This ensures that paths are properly scoped and differentiated when working with multiple services

Paths in the Swagger JSON do not contain the necessary serviceName prefix, which leads to incorrect or ambiguous routes in the API documentation

To resolve this issue, I added logic that prefixes the serviceName to each path in the Swagger JSON. This is implemented via the AddServiceNamePrefixToPaths method, which is called within the SwaggerForOcelotMiddleware.

Steps to Reproduce

Suggested Fix Implement the AddServiceNamePrefixToPaths method to automatically add the serviceName prefix to all paths in the Swagger JSON, ensuring correct routing and clarity in API documentation

public string AddServiceNamePrefixToPaths(string swaggerJson, SwaggerEndPointOptions endPoint, string version)
    {
        var config = string.IsNullOrEmpty(version)
            ? endPoint.Config.FirstOrDefault()
            : endPoint.Config.FirstOrDefault(x => x.Version == version);

        var serviceName = config?.Service?.Name;
        if (string.IsNullOrEmpty(serviceName))
            return swaggerJson;

        if (!swaggerJson.TryParse(out var swaggerObj))
            return swaggerJson;

        if (!swaggerObj.TryGetValue(OpenApiProperties.Paths, out var swaggerPaths))
            return swaggerJson;

        if (swaggerPaths is not JObject pathsObj)
            return swaggerJson;

        var properties = pathsObj.Properties().ToList();
        properties.ForEach(f => SetToPathServiceName(f, pathsObj, serviceName));

        return swaggerObj.ToString();
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="jProperty"></param>
    /// <param name="pathsObj"></param>
    /// <param name="serviceName"></param>
    private void SetToPathServiceName(JProperty jProperty, JObject pathsObj, string serviceName)
    {
        jProperty.Remove();

        var path = $"/{serviceName}{jProperty.Name}";
        pathsObj.Add(path, jProperty.Value);
    }
rabdulatif commented 1 month ago

i have some code corrections. After this i will reopen PR

rabdulatif commented 1 month ago

PR renewed please check, if possible can make Nuget Package for new Lib also? Thanks

@Burgyn