Код: Выделить всё
npx openapi-typescript https://localhost:7088/openapi/v1.json -o ./apiSchema.ts --enumПоскольку реализация OpenAPI по умолчанию в Net9 генерирует только enum как целые числа, которые я изучал в трансформаторах схемы. Однако я не полностью узнал, как их использовать и не нашел документы, которые помогли мне с проблемой, что она удваивает схему. < /P>
Код: Выделить всё
var enumCache = new Dictionary();
options.AddSchemaTransformer(async delegate(
OpenApiSchema schema,
OpenApiSchemaTransformerContext context,
CancellationToken ct)
{
if (context?.JsonPropertyInfo?.PropertyType.IsEnum == true)
{
if (enumCache.TryGetValue(context.JsonPropertyInfo.PropertyType, out var enumSchema))
{
Console.WriteLine($"prop: {context?.JsonPropertyInfo?.Name}: enumSchema:{enumSchema} - from cache");
schema = enumSchema;
return;
}
var enumNames = Enum.GetNames(context.JsonPropertyInfo.PropertyType);
var enumValues = Enum.GetValues(context.JsonPropertyInfo.PropertyType);
var enumDesc = enumValues.Cast().Select(
(value, index) =>
{
// get description attribute via reflection
var attr = context.JsonPropertyInfo.PropertyType.GetField(value.ToString())?
.GetCustomAttribute();
return new
{
Value = (int) value,
Name = enumNames[index],
Description = attr?.Description
};
});
var openApiValueArray = new OpenApiArray();
var openApiNameArray = new OpenApiArray();
var openApiDescArray = new OpenApiArray();
foreach (var item in enumDesc)
{
openApiValueArray.Add(new OpenApiInteger(item.Value));
openApiNameArray.Add(new OpenApiString(item.Name));
openApiDescArray.Add(new OpenApiString(item.Description));
}
schema.Extensions.Add("x-enum-varnames", openApiNameArray); // https://openapi-ts.dev/advanced#enum-extensions
schema.Extensions.Add("x-enum-descriptions", openApiDescArray);
schema.Extensions.Add("enum", openApiValueArray);
enumCache[context.JsonPropertyInfo.PropertyType] = schema;
return;
}
return;
});
< /code>
Это (частичный) пример, где типы удваиваются. Это также влияет на все содержащие типы и конечные точки, затем использует неправильную «старую» схему. < /P>
"WorldStatus": {
"type": "integer",
"x-enum-varnames": [
"Active",
"Maintenance",
"Full",
"Ended"
],
"x-enum-descriptions": [
null,
null,
null,
"game over"
],
"enum": [
0,
1,
2,
3
]
},
"WorldStatus2": {
"type": "integer"
}
< /code>
test enum: < /p>
public enum WorldStatus
{
Active,
Maintenance,
Full,
[Description("game over")]
Ended
}
Подробнее здесь: https://stackoverflow.com/questions/795 ... -with-net9