Skip to content

Instantly share code, notes, and snippets.

@Xor-el
Created May 13, 2024 20:57
Show Gist options
  • Save Xor-el/dfec7c1d52b64feb4354b8f19b178a0b to your computer and use it in GitHub Desktop.
Save Xor-el/dfec7c1d52b64feb4354b8f19b178a0b to your computer and use it in GitHub Desktop.
Swagger Utils to generate Schema Id
static class SwashBuckleUtils
{
private static readonly Dictionary<Type, string> _map = new Dictionary<Type, string>();
private static string ToSchemaId(Type type, bool skipDeclaringType)
{
if (!_map.TryGetValue(type, out var name))
{
if (type.IsGenericType && !type.IsGenericTypeDefinition)
{
var genericTypeName = type.GetGenericTypeDefinition().Name;
// Check if it's a real generic type. Non-generic types nested in generic types will also have IsGenericType() == true but won't have a '`' in their name
// "Real" generic type names must be trimmed to exclude everything after '`' including that character.
int p = genericTypeName.IndexOf('`');
if (p > 0)
genericTypeName = genericTypeName[..p];
name = $"{genericTypeName}Of{string.Join("And", type.GetGenericArguments().Select(t => ToSchemaId(t, skipDeclaringType: true)))}";
}
else
{
// the .Replace() handles the case of nested types, since '+' is not a valid schema id character
name = type.Namespace + '.' + type.Name.Replace('+', '_');
if (type.DeclaringType is not null && !skipDeclaringType)
name = ToSchemaId(type.DeclaringType) + '_' + name;
}
_map[type] = name;
}
return name;
}
public static string ToSchemaId(Type type)
{
var name = ToSchemaId(type, skipDeclaringType: false);
return name;
}
public static IEnumerable<Type> AnnotationsKnownTypesSelector(Type type)
{
var subtypes = new List<Type>();
foreach (var knownTypeAttribute in type.GetCustomAttributes(false).OfType<KnownTypeAttribute>())
{
if (knownTypeAttribute.Type is not null)
subtypes.Add(knownTypeAttribute.Type);
else if (knownTypeAttribute.MethodName is not null)
throw new InvalidOperationException($"{type}: KnownType(\"{knownTypeAttribute.MethodName}\") is not supported");
}
return subtypes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment