-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathOpenApi.cs
More file actions
694 lines (609 loc) · 23 KB
/
Copy pathOpenApi.cs
File metadata and controls
694 lines (609 loc) · 23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using Npgsql;
using static NpgsqlRest.NpgsqlRestOptions;
namespace NpgsqlRest.OpenAPI;
[JsonSerializable(typeof(JsonObject))]
internal partial class OpenApiSerializerContext : JsonSerializerContext;
public class OpenApi(OpenApiOptions openApiOptions) : IEndpointCreateHandler
{
public OpenApi() : this(new OpenApiOptions()) { }
private IApplicationBuilder _builder = default!;
private JsonObject _document = default!;
private JsonObject _paths = default!;
private JsonObject _schemas = default!;
private JsonObject? _securitySchemes = null;
public void Setup(IApplicationBuilder builder, NpgsqlRestOptions options)
{
_builder = builder;
// Initialize OpenAPI document structure
var info = new JsonObject
{
["title"] = GetDocumentTitle(),
["version"] = openApiOptions.DocumentVersion
};
if (!string.IsNullOrEmpty(openApiOptions.DocumentDescription))
{
info["description"] = openApiOptions.DocumentDescription;
}
_document = new JsonObject
{
["openapi"] = "3.0.3",
["info"] = info
};
// Add servers section if configured
var servers = BuildServersArray();
if (servers != null && servers.Count > 0)
{
_document["servers"] = servers;
}
_paths = new JsonObject();
_document["paths"] = _paths;
_schemas = new JsonObject();
_document["components"] = new JsonObject
{
["schemas"] = _schemas
};
// Initialize security schemes if configured
if (openApiOptions.SecuritySchemes != null && openApiOptions.SecuritySchemes.Length > 0)
{
_securitySchemes = BuildSecuritySchemes(openApiOptions.SecuritySchemes);
if (_securitySchemes != null && _securitySchemes.Count > 0)
{
_document["components"]!["securitySchemes"] = _securitySchemes;
}
}
}
public void Handle(RoutineEndpoint endpoint)
{
var path = endpoint.Path;
var method = endpoint.Method.ToString().ToLowerInvariant();
// Initialize path object if it doesn't exist
if (!_paths.ContainsKey(path))
{
_paths[path] = new JsonObject();
}
var pathItem = _paths[path] as JsonObject;
var operation = new JsonObject();
// Add operation summary and description
if (!string.IsNullOrEmpty(endpoint.Routine.Comment))
{
var lines = endpoint.Routine.Comment.Split('\n', StringSplitOptions.RemoveEmptyEntries);
operation["summary"] = lines[0].Trim();
if (lines.Length > 1)
{
operation["description"] = string.Join("\n", lines.Skip(1).Select(l => l.Trim()));
}
}
else
{
operation["summary"] = $"{endpoint.Routine.Type} {endpoint.Routine.Schema}.{endpoint.Routine.Name}";
}
// Add tags based on schema
operation["tags"] = new JsonArray(endpoint.Routine.Schema);
// Add operation ID
operation["operationId"] = $"{endpoint.Routine.Schema}_{endpoint.Routine.Name}_{method}";
// Add parameters
var parameters = new JsonArray();
// Add path parameters first (if any)
if (endpoint.HasPathParameters)
{
foreach (var pathParamName in endpoint.PathParameters!)
{
// Find the matching routine parameter to get its type
var routineParam = endpoint.Routine.Parameters
.FirstOrDefault(p =>
string.Equals(p.ConvertedName, pathParamName, StringComparison.OrdinalIgnoreCase) ||
string.Equals(p.ActualName, pathParamName, StringComparison.OrdinalIgnoreCase));
var pathParameter = new JsonObject
{
["name"] = routineParam?.ConvertedName ?? pathParamName,
["in"] = "path",
["required"] = true // Path parameters are always required in OpenAPI
};
if (routineParam != null)
{
pathParameter["schema"] = GetSchemaForType(routineParam.TypeDescriptor);
}
else
{
// Default to string if parameter not found
pathParameter["schema"] = new JsonObject { ["type"] = "string" };
}
parameters.Add((JsonNode)pathParameter);
}
}
if (endpoint.Routine.Parameters.Length > 0)
{
if (endpoint.RequestParamType == RequestParamType.QueryString)
{
foreach (var param in endpoint.Routine.Parameters)
{
// Skip body parameter if it exists
if (endpoint.BodyParameterName is not null &&
(string.Equals(param.ConvertedName, endpoint.BodyParameterName, StringComparison.Ordinal) ||
string.Equals(param.ActualName, endpoint.BodyParameterName, StringComparison.Ordinal)))
{
continue;
}
// Skip path parameters - they are already added above
if (endpoint.HasPathParameters)
{
var isPathParam = false;
foreach (var pathParam in endpoint.PathParameters!)
{
if (string.Equals(param.ConvertedName, pathParam, StringComparison.OrdinalIgnoreCase) ||
string.Equals(param.ActualName, pathParam, StringComparison.OrdinalIgnoreCase))
{
isPathParam = true;
break;
}
}
if (isPathParam)
{
continue;
}
}
var parameter = new JsonObject
{
["name"] = param.ConvertedName,
["in"] = "query",
["required"] = !param.TypeDescriptor.HasDefault,
["schema"] = GetSchemaForType(param.TypeDescriptor)
};
parameters.Add((JsonNode)parameter);
}
}
else if (endpoint.RequestParamType == RequestParamType.BodyJson)
{
// Add request body for JSON, excluding path parameters
var requestSchema = new JsonObject
{
["type"] = "object",
["properties"] = new JsonObject()
};
var properties = requestSchema["properties"] as JsonObject;
var required = new JsonArray();
foreach (var param in endpoint.Routine.Parameters)
{
// Skip path parameters - they should not be in the request body
if (endpoint.HasPathParameters)
{
var isPathParam = false;
foreach (var pathParam in endpoint.PathParameters!)
{
if (string.Equals(param.ConvertedName, pathParam, StringComparison.OrdinalIgnoreCase) ||
string.Equals(param.ActualName, pathParam, StringComparison.OrdinalIgnoreCase))
{
isPathParam = true;
break;
}
}
if (isPathParam)
{
continue;
}
}
properties![param.ConvertedName] = GetSchemaForType(param.TypeDescriptor);
if (!param.TypeDescriptor.HasDefault)
{
required.Add((JsonNode?)JsonValue.Create(param.ConvertedName));
}
}
if (required.Count > 0)
{
requestSchema["required"] = required;
}
// Only add requestBody if there are non-path parameters
if (properties!.Count > 0)
{
operation["requestBody"] = new JsonObject
{
["required"] = true,
["content"] = new JsonObject
{
["application/json"] = new JsonObject
{
["schema"] = requestSchema
}
}
};
}
}
}
if (parameters.Count > 0)
{
operation["parameters"] = parameters;
}
// Handle body parameter in query string mode
if (endpoint.BodyParameterName is not null && endpoint.RequestParamType == RequestParamType.QueryString)
{
var bodyParam = endpoint.Routine.Parameters
.FirstOrDefault(p =>
string.Equals(p.ConvertedName, endpoint.BodyParameterName, StringComparison.Ordinal) ||
string.Equals(p.ActualName, endpoint.BodyParameterName, StringComparison.Ordinal));
if (bodyParam is not null)
{
operation["requestBody"] = new JsonObject
{
["required"] = !bodyParam.TypeDescriptor.HasDefault,
["content"] = new JsonObject
{
["text/plain"] = new JsonObject
{
["schema"] = GetSchemaForType(bodyParam.TypeDescriptor)
}
}
};
}
}
// Add responses
var responses = new JsonObject
{
["200"] = new JsonObject
{
["description"] = "Successful response"
}
};
// Add response content if not void
if (!endpoint.Routine.IsVoid)
{
var responseContent = new JsonObject();
var contentType = endpoint.ResponseContentType ?? "application/json";
if (contentType.Contains("json", StringComparison.OrdinalIgnoreCase))
{
var responseSchema = GetResponseSchema(endpoint.Routine);
responseContent[contentType] = new JsonObject
{
["schema"] = responseSchema
};
}
else
{
// For non-JSON responses
responseContent[contentType] = new JsonObject
{
["schema"] = new JsonObject
{
["type"] = "string"
}
};
}
(responses["200"] as JsonObject)!["content"] = responseContent;
}
operation["responses"] = responses;
// Add security if required
if (endpoint.RequiresAuthorization)
{
// Add security requirements for this operation
if (_securitySchemes != null && _securitySchemes.Count > 0)
{
// Add all configured security schemes as alternatives (OR relationship)
var securityArray = new JsonArray();
foreach (var schemeName in _securitySchemes.AsObject().Select(kv => kv.Key))
{
securityArray.Add((JsonNode)new JsonObject
{
[schemeName] = new JsonArray()
});
}
operation["security"] = securityArray;
}
else
{
// Add default bearer auth if no schemes configured
operation["security"] = new JsonArray(
new JsonObject
{
["bearerAuth"] = new JsonArray()
}
);
// Add default bearer scheme to components if not already there
if (!_document["components"]!.AsObject().ContainsKey("securitySchemes"))
{
_document["components"]!["securitySchemes"] = new JsonObject
{
["bearerAuth"] = new JsonObject
{
["type"] = "http",
["scheme"] = "bearer",
["bearerFormat"] = "JWT"
}
};
}
}
}
pathItem![method] = operation;
}
public void Cleanup()
{
if (openApiOptions.FileName is null && openApiOptions.UrlPath is null)
{
return;
}
var json = JsonSerializer.Serialize(_document, OpenApiSerializerContext.Default.JsonObject);
// Write to file if FileName is specified
if (openApiOptions.FileName is not null)
{
var fullFileName = System.IO.Path.Combine(Environment.CurrentDirectory, openApiOptions.FileName);
if (!openApiOptions.FileOverwrite && File.Exists(fullFileName))
{
Logger?.LogDebug("OpenAPI file already exists and FileOverwrite is false: {fileName}", fullFileName);
}
else
{
var dir = System.IO.Path.GetDirectoryName(fullFileName);
if (dir is not null && Directory.Exists(dir) is false)
{
Directory.CreateDirectory(dir);
}
File.WriteAllText(fullFileName, json);
Logger?.LogDebug("Created OpenAPI file: {fileName}", fullFileName);
}
}
// Serve as endpoint if UrlPath is specified
if (openApiOptions.UrlPath is not null)
{
var path = openApiOptions.UrlPath;
_builder.Use(async (context, next) =>
{
if (string.Equals(context.Request.Method, "GET", StringComparison.OrdinalIgnoreCase) &&
string.Equals(context.Request.Path, path, StringComparison.Ordinal))
{
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(json);
return;
}
await next(context);
});
var host = GetHost();
Logger?.LogDebug("Exposed OpenAPI document on URL: {host}{path}", host, path);
}
}
private JsonObject GetSchemaForType(TypeDescriptor type)
{
var schema = new JsonObject();
if (type.IsArray)
{
schema["type"] = "array";
var itemType = new TypeDescriptor(type.Type, type.HasDefault);
schema["items"] = GetSchemaForType(itemType);
return schema;
}
if (type.IsNumeric)
{
if (type.Type.Contains("int", StringComparison.OrdinalIgnoreCase))
{
schema["type"] = "integer";
if (type.Type.Contains("big", StringComparison.OrdinalIgnoreCase) ||
type.Type == "int8")
{
schema["format"] = "int64";
}
else
{
schema["format"] = "int32";
}
}
else
{
schema["type"] = "number";
if (type.Type == "real" || type.Type == "float4")
{
schema["format"] = "float";
}
else if (type.Type == "double precision" || type.Type == "float8")
{
schema["format"] = "double";
}
}
return schema;
}
if (type.IsBoolean)
{
schema["type"] = "boolean";
return schema;
}
if (type.IsDateTime)
{
schema["type"] = "string";
schema["format"] = "date-time";
return schema;
}
if (type.IsDate)
{
schema["type"] = "string";
schema["format"] = "date";
return schema;
}
if (type.Type == "uuid")
{
schema["type"] = "string";
schema["format"] = "uuid";
return schema;
}
if (type.IsJson)
{
schema["type"] = "object";
return schema;
}
// Default to string
schema["type"] = "string";
return schema;
}
private JsonObject GetResponseSchema(Routine routine)
{
if (routine.ReturnsSet)
{
// Returns array of objects
var itemSchema = new JsonObject
{
["type"] = "object",
["properties"] = new JsonObject()
};
var properties = itemSchema["properties"] as JsonObject;
for (int i = 0; i < routine.ColumnCount; i++)
{
properties![routine.ColumnNames[i]] = GetSchemaForType(routine.ColumnsTypeDescriptor[i]);
}
return new JsonObject
{
["type"] = "array",
["items"] = itemSchema
};
}
else if (routine.ColumnCount > 1 || routine.ReturnsRecordType)
{
// Returns single object
var schema = new JsonObject
{
["type"] = "object",
["properties"] = new JsonObject()
};
var properties = schema["properties"] as JsonObject;
for (int i = 0; i < routine.ColumnCount; i++)
{
properties![routine.ColumnNames[i]] = GetSchemaForType(routine.ColumnsTypeDescriptor[i]);
}
return schema;
}
else if (routine.ColumnCount == 1)
{
// Returns single value
return GetSchemaForType(routine.ColumnsTypeDescriptor[0]);
}
// Default
return new JsonObject
{
["type"] = "object"
};
}
private string GetHost()
{
string? host = null;
if (_builder is WebApplication app)
{
if (app.Urls.Count != 0)
{
host = app.Urls.FirstOrDefault();
}
else
{
var section = app.Configuration?.GetSection("ASPNETCORE_URLS");
if (section?.Value is not null)
{
host = section.Value.Split(";")?.LastOrDefault();
}
}
if (host is null && app.Configuration?["urls"] is not null)
{
host = app.Configuration?["urls"];
}
}
// default, assumed host
host ??= "http://localhost:8080";
return host.TrimEnd('/');
}
private string GetDocumentTitle()
{
if (openApiOptions.DocumentTitle is not null)
{
return openApiOptions.DocumentTitle;
}
if (openApiOptions.ConnectionString is not null)
{
return new NpgsqlConnectionStringBuilder(openApiOptions.ConnectionString).Database ??
(openApiOptions.ConnectionString?.Split(";") ?? []).FirstOrDefault(s => s.StartsWith("Database="))
?.Split("=")?.Last() ?? "NpgsqlRest API";
}
return "NpgsqlRest API";
}
private JsonArray? BuildServersArray()
{
var serversArray = new JsonArray();
// Add configured servers first
if (openApiOptions.Servers != null)
{
foreach (var server in openApiOptions.Servers)
{
var serverObj = new JsonObject
{
["url"] = server.Url
};
if (!string.IsNullOrEmpty(server.Description))
{
serverObj["description"] = server.Description;
}
serversArray.Add((JsonNode)serverObj);
}
}
// Add current server if enabled and not already added
if (openApiOptions.AddCurrentServer)
{
var currentHost = GetHost();
// Check if this URL is already in the servers array
var alreadyExists = openApiOptions.Servers?.Any(s =>
string.Equals(s.Url.TrimEnd('/'), currentHost, StringComparison.OrdinalIgnoreCase)) ?? false;
if (!alreadyExists)
{
var currentServerObj = new JsonObject
{
["url"] = currentHost
};
// Add description for current server
if (currentHost.Contains("localhost", StringComparison.OrdinalIgnoreCase))
{
currentServerObj["description"] = "Development server";
}
serversArray.Add((JsonNode)currentServerObj);
}
}
return serversArray.Count > 0 ? serversArray : null;
}
private JsonObject? BuildSecuritySchemes(OpenApiSecurityScheme[] schemes)
{
if (schemes == null || schemes.Length == 0)
{
return null;
}
var securitySchemes = new JsonObject();
foreach (var scheme in schemes)
{
var schemeObj = new JsonObject();
switch (scheme.Type)
{
case OpenApiSecuritySchemeType.Http:
schemeObj["type"] = "http";
if (scheme.Scheme.HasValue)
{
schemeObj["scheme"] = scheme.Scheme.Value.ToString().ToLowerInvariant();
}
if (!string.IsNullOrEmpty(scheme.BearerFormat))
{
schemeObj["bearerFormat"] = scheme.BearerFormat;
}
break;
case OpenApiSecuritySchemeType.ApiKey:
schemeObj["type"] = "apiKey";
if (!string.IsNullOrEmpty(scheme.In))
{
schemeObj["name"] = scheme.In;
}
if (scheme.ApiKeyLocation.HasValue)
{
schemeObj["in"] = scheme.ApiKeyLocation.Value.ToString().ToLowerInvariant();
}
break;
}
if (!string.IsNullOrEmpty(scheme.Description))
{
schemeObj["description"] = scheme.Description;
}
securitySchemes[scheme.Name] = schemeObj;
}
return securitySchemes.Count > 0 ? securitySchemes : null;
}
}