{{ message }}
-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathTsClient.cs
More file actions
367 lines (330 loc) · 12.7 KB
/
Copy pathTsClient.cs
File metadata and controls
367 lines (330 loc) · 12.7 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
using System.Text;
namespace NpgsqlRest.TsClient;
public class TsClient(TsClientOptions options) : IEndpointCreateHandler
{
private IApplicationBuilder _builder = default!;
private ILogger? _logger;
private NpgsqlRestOptions? _npgsqlRestoptions;
public TsClient(string filePath) : this(new TsClientOptions(filePath)) { }
public void Setup(IApplicationBuilder builder, ILogger? logger, NpgsqlRestOptions options)
{
if (builder is WebApplication app)
{
var factory = app.Services.GetRequiredService<ILoggerFactory>();
if (factory is not null)
{
_logger = factory.CreateLogger(options.LoggerName ?? typeof(TsClient).Namespace ?? "NpgsqlRest.HttpFiles");
}
else
{
_logger = app.Logger;
}
}
else
{
_logger = logger;
}
_builder = builder;
_npgsqlRestoptions = options;
}
public void Cleanup(ref (Routine routine, RoutineEndpoint endpoint)[] endpoints)
{
if (options.FilePath is null)
{
return;
}
HashSet<string> models___ = [];
Dictionary<string, string> modelsDict = [];
Dictionary<string, int> names = [];
StringBuilder content = new();
StringBuilder interfaces = new();
content.AppendLine(string.Format(
"""
const _baseUrl = "{0}";
const _parseQuery = (query: Record<any, any>) => "?" + Object.keys(query)
.map(key => {{
const value = query[key] ? query[key] : "";
if (Array.isArray(value)) {{
return value.map(s => s ? `${{key}}=${{encodeURIComponent(s)}}` : `${{key}}=`).join("&");
}}
return `${{key}}=${{encodeURIComponent(value)}}`;
}})
.join("&");
""", GetHost())
);
foreach (var (routine, endpoint) in endpoints
.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))
{
Handle(routine, endpoint);
}
foreach (var (routine, endpoint) in endpoints
.Where(e => (e.routine.Type == RoutineType.Table || e.routine.Type == RoutineType.View) is false)
.OrderBy(e => e.routine.Schema)
.ThenBy(e => e.routine.Name))
{
Handle(routine, endpoint);
}
if (!options.FileOverwrite && File.Exists(options.FilePath))
{
return;
}
interfaces.AppendLine(content.ToString());
File.WriteAllText(options.FilePath, interfaces.ToString());
_logger?.LogInformation("Created Typescript file: {0}", options.FilePath);
return;
void Handle(Routine routine, RoutineEndpoint endpoint)
{
var name = string.IsNullOrEmpty(_npgsqlRestoptions?.UrlPathPrefix) ? endpoint.Url : endpoint.Url[_npgsqlRestoptions.UrlPathPrefix.Length..];
if (routine.Type == RoutineType.Table || routine.Type == 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);
}
var pascal = ConvertToPascalCase(name);
var camel = ConvertToCamelCase(name);
content.AppendLine();
string? requestName = null;
if (routine.ParamCount > 0)
{
StringBuilder req = new();
requestName = $"I{pascal}Request";
for (var i = 0; i < routine.ParamCount; i++)
{
var descriptor = routine.ParamTypeDescriptor[i];
var nameSuffix = descriptor.HasDefault ? "?" : "";
var type = GetTsType(descriptor, true);
req.AppendLine($" {endpoint.ParamNames[i]}{nameSuffix}: {type} | null;");
}
if (modelsDict.TryGetValue(req.ToString(), out var newName))
{
requestName = newName;
}
else
{
modelsDict.Add(req.ToString(), requestName);
req.Insert(0, $"interface {requestName} {{{Environment.NewLine}");
req.AppendLine("}");
req.AppendLine();
interfaces.Append(req);
}
}
string responseName = "void";
bool json = false;
string? returnExp = null;
if (routine.IsVoid is false)
{
if (routine.ReturnsSet == false && routine.ColumnCount == 1 && routine.ReturnsRecordType is false)
{
var descriptor = routine.ColumnsTypeDescriptor[0];
responseName = GetTsType(descriptor, true);
if (descriptor.IsArray)
{
json = true;
returnExp = $"return await response.json() as {responseName}[];";
}
else
{
if (descriptor.IsDate || descriptor.IsDateTime)
{
returnExp = "return new Date(await response.text());";
}
else if (descriptor.IsNumeric)
{
returnExp = "return Number(await response.text());";
}
else if (descriptor.IsBoolean)
{
returnExp = "return (await response.text()).toLowerCase() == \"true\";";
}
else
{
returnExp = "return await response.text();";
}
}
}
else
{
json = true;
if (routine.ReturnsUnnamedSet)
{
responseName = "string[]";
}
else
{
StringBuilder resp = new();
responseName = $"I{pascal}Response";
for (var i = 0; i < routine.ColumnCount; i++)
{
var descriptor = routine.ColumnsTypeDescriptor[i];
var type = GetTsType(descriptor, false);
resp.AppendLine($" {endpoint.ReturnRecordNames[i]}: {type} | null;");
}
if (modelsDict.TryGetValue(resp.ToString(), out var newName))
{
responseName = newName;
}
else
{
modelsDict.Add(resp.ToString(), responseName);
resp.Insert(0, $"interface {responseName} {{{Environment.NewLine}");
resp.AppendLine("}");
resp.AppendLine();
interfaces.Append(resp);
}
}
if (routine.ReturnsSet)
{
responseName = string.Concat(responseName, "[]");
}
returnExp = $"return await response.json() as {responseName};";
}
}
string NewLine(string? input, int ident) =>
input is null ? "" : string.Concat(Environment.NewLine, string.Concat(Enumerable.Repeat(" ", ident)), input);
var headers = json ?
@"headers: { ""Content-Type"": ""application/json"" }," : null;
var body = endpoint.RequestParamType == RequestParamType.BodyJson && requestName is not null ?
@"body: JSON.stringify(request)" : null;
var qs = endpoint.RequestParamType == RequestParamType.QueryString && requestName is not null ? " + _parseQuery(request)" : "";
var funcBody = string.Format(
"""
{0}await fetch(_baseUrl + "{1}"{2}, {{
method: "{3}",{4}{5}
}});{6}
""",
routine.IsVoid ? "" : "const response = ",
endpoint.Url,
qs,
endpoint.Method,
NewLine(headers, 2),
NewLine(body, 2),
NewLine(returnExp, 1));
content.AppendLine(string.Format(
"""
/**
{0}
*/
export async function {1}({2}) : Promise<{3}> {{
{4}
""",
GetComment(routine, endpoint),
camel,
requestName is null ? "" : string.Concat("request: ", requestName),
responseName,
funcBody));
content.AppendLine("}");
} // void Handle
}
private string GetComment(Routine routine, RoutineEndpoint endpoint)
{
StringBuilder sb = new();
if (options.CommentHeader != CommentHeader.None)
{
var comment = options.CommentHeader switch
{
CommentHeader.Simple => routine.SimpleDefinition,
CommentHeader.Full => routine.FullDefinition,
_ => "",
};
foreach (var line in comment.Split('\n', StringSplitOptions.RemoveEmptyEntries))
{
if (line == "\r")
{
continue;
}
sb.AppendLine(string.Concat("* ", line.TrimEnd('\r')));
}
sb.AppendLine("* ");
sb.AppendLine("* @remarks");
sb.AppendLine(string.Format("* {0} {1}", endpoint.Method, endpoint.Url));
}
else
{
sb.AppendLine(string.Format("* {0} {1}", endpoint.Method, endpoint.Url));
}
sb.AppendLine("* ");
sb.Append(string.Format("* @see {0} {1}.{2}", routine.Type.ToString().ToUpperInvariant(), routine.Schema, routine.Name));
return sb.ToString();
}
private static string GetTsType(TypeDescriptor descriptor, bool useDateType)
{
var type = "string";
if (useDateType && (descriptor.IsDate || descriptor.IsDateTime))
{
type = "Date";
}
else if (descriptor.IsNumeric)
{
type = "number";
}
else if (descriptor.IsBoolean)
{
type = "boolean";
}
if (descriptor.IsArray)
{
type = string.Concat(type, "[]");
}
return type;
}
private static readonly char[] separator = ['_', '-', '/', '\\'];
public static string ConvertToPascalCase(string value)
{
return value
.Split(separator, StringSplitOptions.RemoveEmptyEntries)
.Select((s, i) =>
string.Concat(i == 0 ? char.ToUpperInvariant(s[0]) : char.ToUpperInvariant(s[0]), s[1..]))
.Aggregate(string.Empty, string.Concat)
.Trim('"');
}
public static string ConvertToCamelCase(string value)
{
return value
.Split(separator, StringSplitOptions.RemoveEmptyEntries)
.Select((s, i) =>
string.Concat(i == 0 ? char.ToLowerInvariant(s[0]) : char.ToUpperInvariant(s[0]), s[1..]))
.Aggregate(string.Empty, string.Concat)
.Trim('"');
}
private string GetHost()
{
if (options.IncludeHost is false)
{
return "";
}
if (options.CustomHost is not null)
{
return options.CustomHost;
}
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();
}
}
}
// default, assumed host
host ??= "http://localhost:5000";
return host;
}
}
You can’t perform that action at this time.
