-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathClientUtils.mustache
362 lines (328 loc) · 13.8 KB
/
ClientUtils.mustache
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
{{>partial_header}}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
{{#useCompareNetObjects}}
using KellermanSoftware.CompareNetObjects;
{{/useCompareNetObjects}}
{{#useCustomTemplateCode}}
using Newtonsoft.Json;
using {{packageName}}.Model;
{{/useCustomTemplateCode}}
namespace {{packageName}}.Client
{
/// <summary>
/// Utility functions providing some benefit to API client consumers.
/// </summary>
public static class ClientUtils
{
{{#useCompareNetObjects}}
/// <summary>
/// An instance of CompareLogic.
/// </summary>
public static CompareLogic compareLogic;
/// <summary>
/// Static constructor to initialise compareLogic.
/// </summary>
static ClientUtils()
{
{{#equatable}}
ComparisonConfig comparisonConfig = new{{^net70OrLater}} ComparisonConfig{{/net70OrLater}}();
comparisonConfig.UseHashCodeIdentifier = true;
{{/equatable}}
compareLogic = new{{^net70OrLater}} CompareLogic{{/net70OrLater}}({{#equatable}}comparisonConfig{{/equatable}});
}
{{/useCompareNetObjects}}
/// <summary>
/// Sanitize filename by removing the path
/// </summary>
/// <param name="filename">Filename</param>
/// <returns>Filename</returns>
public static string SanitizeFilename(string filename)
{
Match match = Regex.Match(filename, @".*[/\\](.*)$");
return match.Success ? match.Groups[1].Value : filename;
}
/// <summary>
/// Convert params to key/value pairs.
/// Use collectionFormat to properly format lists and collections.
/// </summary>
/// <param name="collectionFormat">The swagger-supported collection format, one of: csv, tsv, ssv, pipes, multi</param>
/// <param name="name">Key name.</param>
/// <param name="value">Value object.</param>
/// <returns>A multimap of keys with 1..n associated values.</returns>
public static Multimap<string, string> ParameterToMultiMap(string collectionFormat, string name, object value)
{
var parameters = new Multimap<string, string>();
if (value is ICollection collection && collectionFormat == "multi")
{
foreach (var item in collection)
{
parameters.Add(name, ParameterToString(item));
}
}
else if (value is IDictionary dictionary)
{
if(collectionFormat == "deepObject") {
foreach (DictionaryEntry entry in dictionary)
{
parameters.Add(name + "[" + entry.Key + "]", ParameterToString(entry.Value));
}
}
else {
foreach (DictionaryEntry entry in dictionary)
{
parameters.Add(entry.Key.ToString(), ParameterToString(entry.Value));
}
}
}
else
{
parameters.Add(name, ParameterToString(value));
}
return parameters;
}
/// <summary>
/// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime.
/// If parameter is a list, join the list with ",".
/// Otherwise just return the string.
/// </summary>
/// <param name="obj">The parameter (header, path, query, form).</param>
/// <param name="configuration">An optional configuration instance, providing formatting options used in processing.</param>
/// <returns>Formatted string.</returns>
public static string ParameterToString(object obj, IReadableConfiguration configuration = null)
{
if (obj is DateTime dateTime)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return dateTime.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat);
if (obj is DateTimeOffset dateTimeOffset)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return dateTimeOffset.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat);
{{#net60OrLater}}
if (obj is DateOnly dateOnly)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15
return dateOnly.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat);
{{/net60OrLater}}
if (obj is bool boolean)
return boolean ? "true" : "false";
if (obj is ICollection collection) {
List<string> entries = new List<string>();
foreach (var entry in collection)
entries.Add(ParameterToString(entry, configuration));
return string.Join(",", entries);
}
if (obj is Enum && HasEnumMemberAttrValue(obj))
return GetEnumMemberAttrValue(obj);
return Convert.ToString(obj, CultureInfo.InvariantCulture);
}
/// <summary>
/// Serializes the given object when not null. Otherwise return null.
/// </summary>
/// <param name="obj">The object to serialize.</param>
/// <returns>Serialized string.</returns>
public static string Serialize(object obj)
{
return obj != null ? Newtonsoft.Json.JsonConvert.SerializeObject(obj) : null;
}
/// <summary>
/// Encode string in base64 format.
/// </summary>
/// <param name="text">string to be encoded.</param>
/// <returns>Encoded string.</returns>
public static string Base64Encode(string text)
{
return Convert.ToBase64String(global::System.Text.Encoding.UTF8.GetBytes(text));
}
/// <summary>
/// Convert stream to byte array
/// </summary>
/// <param name="inputStream">Input stream to be converted</param>
/// <returns>Byte array</returns>
public static byte[] ReadAsBytes(Stream inputStream)
{
using (var ms = new MemoryStream())
{
inputStream.CopyTo(ms);
return ms.ToArray();
}
}
/// <summary>
/// Select the Content-Type header's value from the given content-type array:
/// if JSON type exists in the given array, use it;
/// otherwise use the first one defined in 'consumes'
/// </summary>
/// <param name="contentTypes">The Content-Type array to select from.</param>
/// <returns>The Content-Type header to use.</returns>
public static string SelectHeaderContentType(string[] contentTypes)
{
if (contentTypes.Length == 0)
return null;
foreach (var contentType in contentTypes)
{
if (IsJsonMime(contentType))
return contentType;
}
return contentTypes[0]; // use the first content type specified in 'consumes'
}
/// <summary>
/// Select the Accept header's value from the given accepts array:
/// if JSON exists in the given array, use it;
/// otherwise use all of them (joining into a string)
/// </summary>
/// <param name="accepts">The accepts array to select from.</param>
/// <returns>The Accept header to use.</returns>
public static string SelectHeaderAccept(string[] accepts)
{
if (accepts.Length == 0)
return null;
if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase))
return "application/json";
return string.Join(",", accepts);
}
/// <summary>
/// Provides a case-insensitive check that a provided content type is a known JSON-like content type.
/// </summary>
public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$");
/// <summary>
/// Check if the given MIME is a JSON MIME.
/// JSON MIME examples:
/// application/json
/// application/json; charset=UTF8
/// APPLICATION/JSON
/// application/vnd.company+json
/// </summary>
/// <param name="mime">MIME</param>
/// <returns>Returns True if MIME type is json.</returns>
public static bool IsJsonMime(string mime)
{
if (string.IsNullOrWhiteSpace(mime)) return false;
return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json");
}
/// <summary>
/// Is the Enum decorated with EnumMember Attribute
/// </summary>
/// <param name="enumVal"></param>
/// <returns>true if found</returns>
private static bool HasEnumMemberAttrValue(object enumVal)
{
if (enumVal == null)
throw new ArgumentNullException(nameof(enumVal));
var enumType = enumVal.GetType();
var memInfo = enumType.GetMember(enumVal.ToString() ?? throw new InvalidOperationException());
var attr = memInfo.FirstOrDefault()?.GetCustomAttributes(false).OfType<EnumMemberAttribute>().FirstOrDefault();
if (attr != null) return true;
return false;
}
/// <summary>
/// Get the EnumMember value
/// </summary>
/// <param name="enumVal"></param>
/// <returns>EnumMember value as string otherwise null</returns>
{{^useCustomTemplateCode}}
private static string GetEnumMemberAttrValue(object enumVal)
{{/useCustomTemplateCode}}
{{#useCustomTemplateCode}}
public static string GetEnumMemberAttrValue(object enumVal)
{{/useCustomTemplateCode}}
{
if (enumVal == null)
throw new ArgumentNullException(nameof(enumVal));
var enumType = enumVal.GetType();
var memInfo = enumType.GetMember(enumVal.ToString() ?? throw new InvalidOperationException());
var attr = memInfo.FirstOrDefault()?.GetCustomAttributes(false).OfType<EnumMemberAttribute>().FirstOrDefault();
if (attr != null)
{
return attr.Value;
}
return null;
}
{{#useCustomTemplateCode}}
/// <summary>
/// Tests if value is a System.IO.Stream or list of System.IO.Stream
/// </summary>
/// <param name="items"></param>
public static bool HasFileType(List<OpenApiType> items)
{
foreach (var item in items)
{
if (
item.Value != null &&
(item.Type == "System.IO.Stream" ||
item.Type == "List<System.IO.Stream>")
)
{
return true;
}
}
return false;
}
/// <summary>
/// Sets up a multipart/form-data payload, including binary data.
/// All non-binary data is serialized to JSON
/// </summary>
/// <param name="requestOptions"></param>
/// <param name="items"></param>
public static void SetFormData(RequestOptions requestOptions, List<OpenApiType> items)
{
foreach (var item in items)
{
if (item.Value == null)
{
continue;
}
if (item.Value is Stream stream)
{
requestOptions.FileParameters.Add(item.Name, stream);
continue;
}
if (item.Value is string or int)
{
requestOptions.FormParameters.Add(
item.Name,
item.Value.ToString()
);
continue;
}
if (item.Value is Enum)
{
requestOptions.FormParameters.Add(
item.Name,
JsonConvert.SerializeObject(item.Value).Replace("\"", string.Empty) //strip extra double quotes
);
continue;
}
if (item.Value is List<Stream> streams)
{
for (var i = 0; i < streams.Count; i++)
{
requestOptions.FileParameters.Add(
$"{item.Name}[{i}]",
streams[i]
);
}
continue;
}
requestOptions.FormParameters.Add(
item.Name,
JsonConvert.SerializeObject(item.Value)
);
}
}
{{/useCustomTemplateCode}}
}
}