{{ message }}
-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathDartClient.cs
More file actions
2099 lines (1962 loc) · 83.6 KB
/
Copy pathDartClient.cs
File metadata and controls
2099 lines (1962 loc) · 83.6 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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Text;
using System.Text.RegularExpressions;
using NpgsqlTypes;
using static NpgsqlRest.NpgsqlRestOptions;
namespace NpgsqlRest.DartClient;
public partial class DartClient(DartClientOptions options) : IEndpointCreateHandler
{
private IApplicationBuilder _builder = default!;
private NpgsqlRestOptions? _npgsqlRestoptions;
private const string Enabled = "dartclient";
private const string Module = "dartclient_module";
// SQL-file directory grouping writes tsclient_module — reuse it so both generators group identically.
private const string TsModuleFallback = "tsclient_module";
private const string IncludeStatusCode = "dartclient_status_code";
private const string SseEvents = "dartclient_events";
private const string IncludeParseUrl = "dartclient_parse_url";
private const string IncludeParseRequest = "dartclient_parse_request";
private const string ExportUrl = "dartclient_export_url";
private const string UrlOnly = "dartclient_url_only";
public void Setup(IApplicationBuilder builder, NpgsqlRestOptions npgsqlRestoptions)
{
_builder = builder;
_npgsqlRestoptions = npgsqlRestoptions;
}
private int _filesCreated;
private static string? GetModule(RoutineEndpoint endpoint) =>
endpoint.CustomParameters?.GetValueOrDefault(Module) ??
endpoint.CustomParameters?.GetValueOrDefault(TsModuleFallback);
public void Cleanup(RoutineEndpoint[] endpoints)
{
if (options.FilePath is null)
{
return;
}
_filesCreated = 0;
var containsModuleParam = endpoints.Any(e => GetModule(e) is not null);
if (!options.BySchema && containsModuleParam)
{
Run(endpoints, options.FilePath);
}
else
{
if (!options.FilePath.Contains("{0}"))
{
Logger?.LogError("DartClient Option FilePath doesn't contain {{0}} formatter and BySchema options is true. Some files may be overwritten! Existing...");
return;
}
HashSet<string> processedModules = [];
if (containsModuleParam)
{
foreach (var group in endpoints.GroupBy(GetModule))
{
if (group.Key is null)
{
continue;
}
if (!processedModules.Contains(group.Key))
{
processedModules.Add(group.Key);
}
var filename = string.Format(options.FilePath, group.Key);
Run([.. group], filename);
}
}
foreach (var group in endpoints.GroupBy(e => e.Routine.Schema))
{
var filename = string.Format(options.FilePath, ConvertToSnakeCase(group.Key));
RoutineEndpoint[] groupArray = [.. group.Where(g =>
GetModule(g) is null ||
!processedModules.Contains(GetModule(g) ?? "")
)];
if (groupArray.Length == 0)
{
continue;
}
Run([.. groupArray], filename);
}
}
if (_filesCreated > 0)
{
Logger?.LogDebug("DartClient: Created {count} Dart file(s)", _filesCreated);
}
}
private sealed record DartField(
string DartName,
string JsonKey,
string DartType,
string ReadExpr,
string WriteExpr,
bool OmitNullInJson);
private void Run(RoutineEndpoint[] endpoints, string? fileName)
{
if (fileName is null)
{
return;
}
// Internal-only endpoints have no public HTTP route (404), so a generated client function for one
// would be dead — e.g. a bare-`@mcp` MCP-only routine. Exclude them from the REST client.
RoutineEndpoint[] filtered = [.. endpoints.Where(e => e.InternalOnly is false && e.CustomParameters.ParameterEnabled(Enabled) is not false)];
Dictionary<string, string> modelsDict = [];
Dictionary<string, int> names = [];
// Track generated composite type model classes to avoid duplicates
// Key: composite field signature, Value: generated class name
Dictionary<string, string> compositeTypeModels = [];
// Reserve the status/scaffold class names so a model class can never collide with them.
HashSet<string> usedModelNames = [options.ErrorTypeName, options.ResultTypeName, "SseSubscription"];
List<string> compositeModels = [];
List<string> models = [];
List<string> urlFunctions = [];
List<string> sseFactories = [];
List<string> functions = [];
bool needsStatusTypes = false;
bool needsQuery = false;
bool needsHttp = false;
bool needsSend = false;
bool needsSendParse = false;
bool needsSendMultipart = false;
bool needsSse = false;
bool needsConvert = false;
bool handled = false;
foreach (var endpoint in filtered
.Where(e => e.Routine.Type == RoutineType.Table || e.Routine.Type == RoutineType.View)
.OrderBy(e => e.Routine.Schema)
.ThenBy(e => e.Routine.Type)
.ThenBy(e => e.Routine.Name))
{
if (Handle(endpoint) && !handled)
{
handled = true;
}
}
foreach (var endpoint in filtered
.Where(e => !(e.Routine.Type == RoutineType.Table || e.Routine.Type == RoutineType.View))
.OrderBy(e => e.Routine.Schema)
.ThenBy(e => e.Routine.Name))
{
if (Handle(endpoint) && !handled)
{
handled = true;
}
}
if (!handled)
{
if (filtered.Length == 0 && options.FileOverwrite)
{
if (File.Exists(fileName))
{
try
{
File.Delete(fileName);
Logger?.LogTrace("Deleted file: {fileName}", fileName);
}
catch (Exception ex)
{
Logger?.LogError(ex, "Failed to delete file: {fileName}", fileName);
try
{
File.WriteAllText(fileName, "// No endpoints found.");
}
catch (Exception ex2)
{
Logger?.LogError(ex2, "Failed to empty file: {fileName}", fileName);
}
}
}
}
return;
}
if (!options.FileOverwrite && File.Exists(fileName))
{
return;
}
var dir = Path.GetDirectoryName(fileName);
if (dir is not null && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
List<string> modelBlocks = [];
if (needsStatusTypes)
{
modelBlocks.Add(GetStatusClasses());
}
modelBlocks.AddRange(compositeModels);
modelBlocks.AddRange(models);
var baseNoExt = Path.GetFileNameWithoutExtension(fileName);
var separateModels = options.SeparateModelsFile && modelBlocks.Count > 0;
if (needsSse)
{
// The SSE scaffold uses utf8.decoder and LineSplitter.
needsConvert = true;
}
List<string> imports = [];
if (needsSse)
{
imports.Add("import 'dart:async';");
}
if (needsConvert)
{
imports.Add("import 'dart:convert';");
}
if (needsSse)
{
imports.Add("import 'dart:math' as math;");
}
if (needsHttp)
{
imports.Add("import 'package:http/http.dart' as http;");
}
foreach (var import in options.CustomImports)
{
imports.Add(import);
}
if (options.ImportBaseUrlFrom is not null)
{
imports.Add($"import '{options.ImportBaseUrlFrom}';");
}
if (separateModels)
{
imports.Add($"import '{baseNoExt}_models.dart';");
imports.Add($"export '{baseNoExt}_models.dart';");
}
List<string> blocks = [];
var headerBlock = GetHeaderBlock();
if (headerBlock is not null)
{
blocks.Add(headerBlock);
}
if (imports.Count > 0)
{
blocks.Add(string.Join(Environment.NewLine, imports));
}
if (options.ImportBaseUrlFrom is null)
{
blocks.Add($"String baseUrl = '{GetHost()}';");
}
if (needsHttp)
{
blocks.Add(ClientScaffold);
}
if (needsSend)
{
blocks.Add(needsSendParse ? SendScaffoldWithParse : SendScaffold);
}
if (needsSendMultipart)
{
blocks.Add(SendMultipartScaffold);
}
if (needsQuery)
{
blocks.Add(QueryScaffold);
}
if (needsSse)
{
blocks.Add(SseScaffold);
}
if (needsStatusTypes)
{
blocks.Add(GetErrorHelper());
}
blocks.AddRange(urlFunctions);
blocks.AddRange(sseFactories);
if (!separateModels)
{
blocks.AddRange(modelBlocks);
}
blocks.AddRange(functions);
File.WriteAllText(fileName, string.Concat(string.Join(string.Concat(Environment.NewLine, Environment.NewLine), blocks), Environment.NewLine));
_filesCreated++;
Logger?.LogTrace("Created Dart file: {fileName}", fileName);
if (separateModels)
{
var modelsFileName = Path.Combine(dir ?? "", string.Concat(baseNoExt, "_models.dart"));
List<string> modelFileBlocks = [];
if (headerBlock is not null)
{
modelFileBlocks.Add(headerBlock);
}
modelFileBlocks.AddRange(modelBlocks);
File.WriteAllText(modelsFileName, string.Concat(string.Join(string.Concat(Environment.NewLine, Environment.NewLine), modelFileBlocks), Environment.NewLine));
_filesCreated++;
Logger?.LogTrace("Created Dart models file: {modelsFileName}", modelsFileName);
}
return;
string? GetHeaderBlock()
{
if (options.HeaderLines.Count == 0)
{
return null;
}
var now = DateTime.Now.ToString("O");
var text = string.Join(Environment.NewLine, options.HeaderLines.Select(l => string.Format(l, now).Trim())).Trim();
return text.Length == 0 ? null : text;
}
bool Handle(RoutineEndpoint endpoint)
{
Routine routine = endpoint.Routine;
var eventsStreamingEnabled = endpoint.SseEventsPath is not null;
if (endpoint.CustomParameters.ParameterEnabled(SseEvents) is false)
{
eventsStreamingEnabled = false;
}
var includeParseUrlParam = endpoint.CustomParameters.ParameterEnabled(IncludeParseUrl) ?? options.IncludeParseUrlParam;
var includeParseRequestParam = endpoint.CustomParameters.ParameterEnabled(IncludeParseRequest) ?? options.IncludeParseRequestParam;
var includeStatusCode = endpoint.CustomParameters.ParameterEnabled(IncludeStatusCode) ?? options.IncludeStatusCode;
var exportUrl = endpoint.CustomParameters.ParameterEnabled(ExportUrl) ?? options.ExportUrls;
var urlOnly = endpoint.CustomParameters.ParameterEnabled(UrlOnly) is true;
if (urlOnly)
{
exportUrl = true;
}
if (options.SkipRoutineNames.Contains(routine.Name))
{
return false;
}
if (options.SkipSchemas.Contains(routine.Schema))
{
return false;
}
if (options.SkipPaths.Contains(endpoint.Path))
{
return false;
}
string? name;
try
{
if (options.UseRoutineNameInsteadOfEndpoint)
{
name = options.IncludeSchemaInNames ? string.Concat(routine.Schema, "/", routine.Name) : routine.Name;
}
else
{
string pathName;
if (string.IsNullOrEmpty(_npgsqlRestoptions?.UrlPathPrefix) || _npgsqlRestoptions.UrlPathPrefix.Length > endpoint.Path.Length)
{
pathName = endpoint.Path;
}
else
{
pathName = endpoint.Path[_npgsqlRestoptions.UrlPathPrefix.Length..];
}
name = options.IncludeSchemaInNames ? string.Concat(routine.Schema, "/", pathName) : pathName;
}
}
catch
{
name = options.IncludeSchemaInNames ? string.Concat(routine.Schema, "/", routine.Name) : routine.Name;
}
if (name.Length < 3)
{
name = options.IncludeSchemaInNames ? string.Concat(routine.Schema, "/", routine.Name) : routine.Name;
}
var routineType = routine.Type;
var paramCount = routine.ParamCount;
var isVoid = routine.IsVoid;
var returnsSet = routine.ReturnsSet;
var columnCount = routine.ColumnCount;
var returnsRecordType = routine.ReturnsRecordType;
var columnsTypeDescriptor = routine.ColumnsTypeDescriptor;
var returnsUnnamedSet = routine.ReturnsUnnamedSet;
if (endpoint.Login)
{
isVoid = false;
returnsSet = false;
columnCount = 1;
returnsRecordType = false;
columnsTypeDescriptor = [new TypeDescriptor("text")];
}
if (endpoint.Logout)
{
isVoid = true;
}
if (routineType == RoutineType.Table || routineType == RoutineType.View)
{
name = string.Concat(name, "-", endpoint.Method.ToString().ToLowerInvariant());
}
if (names.TryGetValue(name, out var count))
{
names[name] = count + 1;
name = string.Concat(name, "-", count);
}
else
{
names.Add(name, 1);
}
name = SanitizeDartName(name);
var pascal = ConvertToPascalCase(name);
var camel = EscapeDartIdentifier(ConvertToCamelCase(name));
// A top-level function must not collide with the module-scaffold declarations.
if (camel is "baseUrl" or "httpClient")
{
camel = string.Concat(camel, "_");
}
if (options.SkipFunctionNames.Contains(camel))
{
return false;
}
// Request fields
string? requestName = null;
List<(DartField Field, bool IsPathParam, bool IsBodyParam, bool HasDefault)> requestFields = [];
Dictionary<string, string> paramFieldByName = new(StringComparer.OrdinalIgnoreCase);
var seenFieldNames = new HashSet<string>(StringComparer.Ordinal);
string? bodyParameterDartName = null;
string? bodyParameterDartType = null;
int requestParamCount = 0;
for (var i = 0; i < paramCount; i++)
{
var parameter = routine.Parameters[i];
var descriptor = parameter.TypeDescriptor;
if (options.OmitAutomaticParameters && endpoint.OmitParameterFromGeneratedRequest(parameter))
{
continue;
}
var dartName = EscapeDartIdentifier(ConvertToCamelCase(SanitizeDartName(parameter.ConvertedName)));
// Skip duplicate parameter names (e.g., when multiple HTTP custom types share field names)
if (!seenFieldNames.Add(dartName))
{
continue;
}
requestParamCount++;
paramFieldByName[parameter.ConvertedName] = dartName;
paramFieldByName.TryAdd(parameter.ActualName, dartName);
var hasDefault = descriptor.HasDefault || descriptor.CustomType is not null;
var isPathParam = endpoint.PathParameters is not null &&
(endpoint.PathParameters.Contains(parameter.ConvertedName, StringComparer.OrdinalIgnoreCase) ||
endpoint.PathParameters.Contains(parameter.ActualName, StringComparer.OrdinalIgnoreCase));
var isBodyParam = endpoint.IsBodyParameter(parameter);
var dartType = GetDartType(descriptor);
var field = new DartField(
dartName,
parameter.ConvertedName,
NullableType(dartType),
GetReadExpr(descriptor, parameter.ConvertedName),
GetWriteExpr(descriptor, dartName),
hasDefault);
requestFields.Add((field, isPathParam, isBodyParam, hasDefault));
if (isBodyParam)
{
bodyParameterDartName = dartName;
bodyParameterDartType = dartType;
}
}
if (requestParamCount > 0)
{
requestName = EscapeDartClassName(string.Concat(options.ModelPrefix, pascal, "Request", options.ModelSuffix));
requestName = AddModel(requestName, [.. requestFields.Select(f => f.Field)]);
}
// Response
string responseName = "void";
bool json = false;
bool responseIsRaw = false;
string[]? payloadLines = null;
string JsonDecodeExpr = "jsonDecode(utf8.decode(response.bodyBytes))";
// proxy_out: always returns the raw upstream response (function runs first, then proxies
// to upstream). Void proxy pass-through likewise. There is no typed Dart shape for those,
// so the generated function returns http.Response directly. Transform proxies (non-void
// @proxy routines) return processed data and fall through to normal handling.
if ((endpoint.IsProxyOut || (endpoint.IsProxy && routine.IsVoid)) && !urlOnly)
{
responseIsRaw = true;
includeStatusCode = false;
responseName = "http.Response";
payloadLines = ["response"];
}
else if (routine.IsMultiCommand && routine.MultiCommandInfo is not null && !urlOnly)
{
// Multi-command SQL file: generate response class with one field per command result
List<DartField> mcFields = [];
foreach (var cmdInfo in routine.MultiCommandInfo)
{
if (cmdInfo.IsSkipped)
{
continue;
}
var fieldName = EscapeDartIdentifier(ConvertToCamelCase(SanitizeDartName(cmdInfo.Name)));
if (cmdInfo.ColumnCount == 0)
{
// Void command → rows affected count
mcFields.Add(new DartField(fieldName, cmdInfo.Name, "int?",
$"(json['{cmdInfo.Name}'] as num?)?.toInt()", fieldName, false));
}
else if (cmdInfo.ColumnCount == 1 && cmdInfo.ReturnsUnnamedSet)
{
// Single column with UnnamedSingleColumnSet — flat list or scalar with @single
var elem = GetElementInfo(cmdInfo.ColumnTypeDescriptors[0]);
if (cmdInfo.IsSingle)
{
mcFields.Add(new DartField(fieldName, cmdInfo.Name, NullableType(elem.Type),
GetReadExpr(cmdInfo.ColumnTypeDescriptors[0], cmdInfo.Name, forceScalar: true),
fieldName, false));
}
else
{
mcFields.Add(new DartField(fieldName, cmdInfo.Name, NullableType($"List<{elem.Type}>"),
elem.Conversion is null
? $"json['{cmdInfo.Name}'] as List?"
: $"(json['{cmdInfo.Name}'] as List?)?.map((e) => {elem.Conversion}).toList()",
fieldName, false));
}
}
else
{
// Named columns — nested class, list or single object with @single
List<DartField> cmdFields = [];
for (int ci = 0; ci < cmdInfo.ColumnCount; ci++)
{
var colName = cmdInfo.ColumnNames[ci];
var colDartName = EscapeDartIdentifier(ConvertToCamelCase(SanitizeDartName(colName)));
var colDescriptor = cmdInfo.ColumnTypeDescriptors[ci];
cmdFields.Add(new DartField(colDartName, colName,
NullableType(GetDartType(colDescriptor)),
GetReadExpr(colDescriptor, colName),
GetWriteExpr(colDescriptor, colDartName), false));
}
var cmdClassName = EscapeDartClassName(string.Concat(
options.ModelPrefix, pascal, ConvertToPascalCase(SanitizeDartName(cmdInfo.Name)), "Result", options.ModelSuffix));
cmdClassName = AddModel(cmdClassName, cmdFields);
if (cmdInfo.IsSingle)
{
mcFields.Add(new DartField(fieldName, cmdInfo.Name, string.Concat(cmdClassName, "?"),
$"json['{cmdInfo.Name}'] == null ? null : {cmdClassName}.fromJson(json['{cmdInfo.Name}'] as Map<String, dynamic>)",
$"{fieldName}?.toJson()", false));
}
else
{
mcFields.Add(new DartField(fieldName, cmdInfo.Name, $"List<{cmdClassName}>?",
$"(json['{cmdInfo.Name}'] as List?)?.map((e) => {cmdClassName}.fromJson(e as Map<String, dynamic>)).toList()",
$"{fieldName}?.map((e) => e.toJson()).toList()", false));
}
}
}
responseName = EscapeDartClassName(string.Concat(options.ModelPrefix, pascal, "Response", options.ModelSuffix));
responseName = AddModel(responseName, mcFields);
json = true;
payloadLines = [$"{responseName}.fromJson({JsonDecodeExpr} as Map<String, dynamic>)"];
}
else if (!isVoid && !urlOnly)
{
if (endpoint.Upload)
{
var uploadName = EscapeDartClassName(string.Concat(options.ModelPrefix, pascal, "Response", options.ModelSuffix));
if (!usedModelNames.Contains(uploadName))
{
usedModelNames.Add(uploadName);
models.Add(RenderUploadModel(uploadName));
}
responseName = $"List<{uploadName}>";
// Note: json flag stays false because upload endpoints use multipart form data,
// and the Content-Type header is set by the multipart request itself.
payloadLines =
[
$"({JsonDecodeExpr} as List)",
$".map((e) => {uploadName}.fromJson(e as Map<String, dynamic>))",
".toList()",
];
}
else if (returnsSet == false && columnCount == 1 && !returnsRecordType)
{
var descriptor = columnsTypeDescriptor[0];
if (descriptor.IsArray)
{
json = true;
var elem = GetElementInfo(descriptor);
responseName = $"List<{elem.Type}>";
payloadLines = elem.Conversion is null
? [$"{JsonDecodeExpr} as List"]
:
[
$"({JsonDecodeExpr} as List)",
$".map((e) => {elem.Conversion})",
".toList()",
];
}
else
{
if ((descriptor.IsDate || descriptor.IsDateTime) && options.UseDateTimeType)
{
responseName = "DateTime";
payloadLines = ["DateTime.parse(utf8.decode(response.bodyBytes))"];
}
else if (descriptor.IsNumeric)
{
responseName = IsIntegerFamily(descriptor) ? "int" : "double";
payloadLines = [$"{responseName}.parse(utf8.decode(response.bodyBytes))"];
}
else if (descriptor.IsBoolean)
{
responseName = "bool";
payloadLines = ["utf8.decode(response.bodyBytes) == 't'"];
}
else if (descriptor.IsJson)
{
responseName = options.DefaultJsonType;
payloadLines = [JsonDecodeExpr];
}
else
{
responseName = "String";
payloadLines = ["utf8.decode(response.bodyBytes)"];
}
}
}
else
{
json = true;
if (returnsUnnamedSet)
{
var descriptor = columnCount > 0 ? columnsTypeDescriptor[0] : new TypeDescriptor("text");
var elem = GetElementInfo(descriptor);
if (returnsSet && !endpoint.ReturnSingleRecord)
{
responseName = $"List<{elem.Type}>";
payloadLines = elem.Conversion is null
? [$"{JsonDecodeExpr} as List"]
:
[
$"({JsonDecodeExpr} as List)",
$".map((e) => {elem.Conversion})",
".toList()",
];
}
else
{
responseName = elem.Type;
payloadLines = [GetScalarJsonExpr(descriptor, JsonDecodeExpr)];
}
}
else
{
List<DartField> responseFields = [];
// Check if nested JSON for composite types is enabled
// When false (default), composite fields are flattened in the JSON response
// When true, composite fields are nested under their column name
var useNestedCompositeTypes = endpoint.NestedJsonForCompositeTypes == true;
// Collect column indices to skip (expanded composite columns) - only when using nested types
HashSet<int> skipIndices = [];
if (useNestedCompositeTypes && routine.CompositeColumnInfo is not null)
{
foreach (var kvp in routine.CompositeColumnInfo)
{
// Skip all expanded column indices except the first one (which becomes the composite property)
foreach (var idx in kvp.Value.ExpandedColumnIndices.Skip(1))
{
skipIndices.Add(idx);
}
}
}
for (var i = 0; i < columnCount; i++)
{
// Skip expanded composite columns (only when nested types are enabled)
if (skipIndices.Contains(i))
{
continue;
}
// Nested composite column - only generate a nested class when NestedJsonForCompositeTypes is true
if (useNestedCompositeTypes &&
routine.CompositeColumnInfo is not null &&
routine.CompositeColumnInfo.TryGetValue(i, out var compositeInfo))
{
var compositeClassName = GetOrCreateCompositeModel(
compositeInfo.FieldNames,
compositeInfo.FieldDescriptors,
compositeInfo.ConvertedColumnName,
compositeTypeModels,
compositeModels);
responseFields.Add(CompositeField(compositeInfo.ConvertedColumnName, compositeClassName));
continue;
}
// Array of composite types
if (routine.ArrayCompositeColumnInfo is not null &&
routine.ArrayCompositeColumnInfo.TryGetValue(i, out var arrayCompositeInfo))
{
var compositeClassName = GetOrCreateCompositeModel(
arrayCompositeInfo.FieldNames,
arrayCompositeInfo.FieldDescriptors,
routine.ColumnNames[i],
compositeTypeModels,
compositeModels);
responseFields.Add(CompositeArrayField(routine.ColumnNames[i], compositeClassName));
continue;
}
var descriptor = columnsTypeDescriptor[i];
// SQL file composite type column: expand fields to match actual JSON response
if (descriptor.IsCompositeType &&
descriptor.CompositeFieldNames is not null &&
descriptor.CompositeFieldDescriptors is not null)
{
if (useNestedCompositeTypes)
{
// Nested mode: generate nested class under column name
var compositeClassName = GetOrCreateCompositeModel(
descriptor.CompositeFieldNames,
descriptor.CompositeFieldDescriptors,
routine.ColumnNames[i],
compositeTypeModels,
compositeModels);
responseFields.Add(CompositeField(routine.ColumnNames[i], compositeClassName));
}
else
{
// Flat mode: inline each composite field as a separate property
for (var fi = 0; fi < descriptor.CompositeFieldNames.Length; fi++)
{
var fieldName = ConvertToCamelCase(descriptor.CompositeFieldNames[fi]);
var fieldDescriptor = descriptor.CompositeFieldDescriptors[fi];
// Handle nested composite fields
if (fieldDescriptor.CompositeFieldNames is not null &&
fieldDescriptor.CompositeFieldDescriptors is not null)
{
var nestedClassName = GetOrCreateCompositeModel(
fieldDescriptor.CompositeFieldNames,
fieldDescriptor.CompositeFieldDescriptors,
fieldName,
compositeTypeModels,
compositeModels);
responseFields.Add(CompositeField(fieldName, nestedClassName));
}
else if (fieldDescriptor.ArrayCompositeFieldNames is not null &&
fieldDescriptor.ArrayCompositeFieldDescriptors is not null)
{
var nestedClassName = GetOrCreateCompositeModel(
fieldDescriptor.ArrayCompositeFieldNames,
fieldDescriptor.ArrayCompositeFieldDescriptors,
fieldName,
compositeTypeModels,
compositeModels);
responseFields.Add(CompositeArrayField(fieldName, nestedClassName));
}
else
{
responseFields.Add(PlainField(fieldName, fieldDescriptor));
}
}
}
continue;
}
responseFields.Add(PlainField(routine.ColumnNames[i], descriptor));
}
responseName = EscapeDartClassName(string.Concat(options.ModelPrefix, pascal, "Response", options.ModelSuffix));
responseName = AddModel(responseName, responseFields);
if (returnsSet && !endpoint.ReturnSingleRecord)
{
payloadLines =
[
$"({JsonDecodeExpr} as List)",
$".map((e) => {responseName}.fromJson(e as Map<String, dynamic>))",
".toList()",
];
responseName = $"List<{responseName}>";
}
else
{
payloadLines = [$"{responseName}.fromJson({JsonDecodeExpr} as Map<String, dynamic>)"];
}
}
}
}
if (includeStatusCode)
{
needsStatusTypes = true;
}
// Headers
Dictionary<string, string> headersDict = [];
if (json)
{
headersDict.Add("Content-Type", "'application/json'");
}
if (eventsStreamingEnabled && _npgsqlRestoptions?.ExecutionIdHeaderName is not null)
{
// Value is the Dart variable holding the execution id, not a string literal.
headersDict.Add(_npgsqlRestoptions.ExecutionIdHeaderName, "executionId");
}
if (options.CustomHeaders.Count > 0)
{
foreach (var header in options.CustomHeaders)
{
if (string.IsNullOrEmpty(header.Value))
{
headersDict.Remove(header.Key);
}
else
{
headersDict[header.Key] = header.Value;
}
}
}
// Body
string? bodyArg = null;
if (endpoint.RequestParamType == RequestParamType.BodyJson && requestName is not null)
{
bodyArg = "jsonEncode(request.toJson())";
}
// Emit the request body for a designated body parameter only when the method can carry one.
// A GET endpoint with @body_parameter_name still excludes that parameter from the query
// string but does not send it as a body — e.g. when it is server-filled (an HTTP Custom
// Type field) and forwarded by a proxy POST upstream.
else if (bodyParameterDartName is not null && endpoint.Method != Method.GET)
{
bodyArg = bodyParameterDartType is "String" or "dynamic"
? $"request.{bodyParameterDartName}"
: $"request.{bodyParameterDartName}?.toString()";
}
// Query string
var hasPathParams = endpoint.HasPathParameters;
var pathParamCount = endpoint.PathParameters?.Length ?? 0;
var bodyParamCount = bodyParameterDartName is not null ? 1 : 0;
// requestParamCount already excludes omitted (server-filled) parameters; path parameters are
// never omitted, so subtracting them and the body parameter yields the query parameter count.
var queryParamCount = requestParamCount - pathParamCount - bodyParamCount;
List<string>? queryEntries = null;
if (endpoint.RequestParamType == RequestParamType.QueryString && requestName is not null && queryParamCount > 0)
{
queryEntries = [];
foreach (var (field, isPathParam, isBodyParam, hasDefault) in requestFields)
{
if (isPathParam || isBodyParam)
{
continue;
}
queryEntries.Add(hasDefault
? $"if (request.{field.DartName} != null) '{field.JsonKey}': request.{field.DartName},"
: $"'{field.JsonKey}': request.{field.DartName},");
}
needsQuery = true;
}
// URL
var pathExpr = hasPathParams
? string.Concat("'$baseUrl", ConvertPathToInterpolation(endpoint.Path, paramFieldByName, routine), "'")
: string.Concat("'$baseUrl", endpoint.Path, "'");
string uriStatement;
// The parseUrl hook reassigns the local, so it cannot be final.
var uriDecl = includeParseUrlParam ? "var" : "final";
var urlFuncName = string.Concat(camel, "Url");
var urlFuncTakesRequest = requestName is not null && (hasPathParams || queryEntries is not null);
if (exportUrl)
{
if (queryEntries is not null)
{
StringBuilder uf = new();
uf.AppendLine($"String {urlFuncName}({(urlFuncTakesRequest ? $"{requestName} request" : "")}) {{");
uf.AppendLine($" return {pathExpr} + _query({{");
foreach (var entry in queryEntries)
{
uf.AppendLine($" {entry}");
}
uf.AppendLine(" });");
uf.Append('}');
urlFunctions.Add(uf.ToString());
}
else
{
urlFunctions.Add($"String {urlFuncName}({(urlFuncTakesRequest ? $"{requestName} request" : "")}) => {pathExpr};");
}
uriStatement = $" {uriDecl} uri = Uri.parse({urlFuncName}({(urlFuncTakesRequest ? "request" : "")}));";
}
else
{
if (queryEntries is not null)
{
StringBuilder us = new();
us.AppendLine($" {uriDecl} uri = Uri.parse({pathExpr} + _query({{");
foreach (var entry in queryEntries)
{
us.AppendLine($" {entry}");
}
us.Append(" }));");
uriStatement = us.ToString();
}
else
{
uriStatement = $" {uriDecl} uri = Uri.parse({pathExpr});";
}
}
if (urlOnly)
{
return true;
}
needsHttp = true;
// SSE event source factory
string? eventSourceFunc = null;
if (eventsStreamingEnabled)
{
needsSse = true;
eventSourceFunc = string.Concat(options.ExportEventSources ? "create" : "_create", pascal, "EventSource");
StringBuilder ef = new();
ef.AppendLine($"Future<SseSubscription> {eventSourceFunc}(");
ef.AppendLine(" void Function(String message) onMessage, {");
ef.AppendLine(" String id = '',");
ef.AppendLine("}) {");
ef.AppendLine(string.Concat(" return _sse(Uri.parse('$baseUrl", endpoint.SseEventsPath, "?$id'), onMessage);"));
ef.Append('}');
sseFactories.Add(ef.ToString());
}
// Result type
string resultType;
if (includeStatusCode)
{
resultType = $"{options.ResultTypeName}<{responseName}>";
}
else
{
resultType = responseName;
}
if ((payloadLines is not null && !responseIsRaw) || bodyArg == "jsonEncode(request.toJson())" || includeStatusCode)
{
needsConvert = true;
}
// Optional named parameters and doc comment
List<string> namedParams = [];
List<(string name, string desc)> paramComments = [];
if (endpoint.Upload)
{
paramComments.Add(("files", "Multipart files to upload, sent as form field \"file\"."));
}
if (requestName is not null)
{
paramComments.Add(("request", "Carries the endpoint parameters."));
}
if (endpoint.Upload)
{
namedParams.Add("void Function(int loaded, int total)? progress");
paramComments.Add(("progress", "Optional callback reporting upload progress in bytes."));
}
if (eventsStreamingEnabled)
{
namedParams.Add("void Function(String message)? onMessage");
paramComments.Add(("onMessage", "Optional callback function to handle incoming SSE messages."));
namedParams.Add("String? id");
paramComments.Add(("id", "Optional execution ID for the SSE connection. When supplied, only event streams opened with this ID in the query string will receive events."));
namedParams.Add("int closeAfterMs = 1000");
paramComments.Add(("closeAfterMs", "Time in milliseconds to wait before closing the SSE connection. Used only when onMessage callback is provided."));
namedParams.Add("int awaitConnectionMs = 0");
paramComments.Add(("awaitConnectionMs", "Time in milliseconds to wait after opening the SSE connection before sending the request. Used only when onMessage callback is provided."));
You can’t perform that action at this time.
