-
Notifications
You must be signed in to change notification settings - Fork 756
/
Copy pathApiClient.mustache
583 lines (529 loc) · 23.2 KB
/
ApiClient.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
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
{{>partial_header}}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using System.IO;
{{^netStandard}}
{{^supportsUWP}}
using System.Web;
{{/supportsUWP}}
{{/netStandard}}
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
{{#netStandard}}
using RestSharp.Portable;
using RestSharp.Portable.HttpClient;
{{/netStandard}}
{{^netStandard}}
using RestSharp;
{{/netStandard}}
using Amazon.SellingPartnerAPIAA;
namespace {{packageName}}.Client
{
/// <summary>
/// API client is mainly responsible for making the HTTP call to the API backend.
/// </summary>
{{>visibility}} partial class ApiClient
{
private LWAAuthorizationSigner lwaAuthorizationSigner;
private AWSSigV4Signer awsSigV4Signer;
private JsonSerializerSettings serializerSettings = new JsonSerializerSettings
{
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};
/// <summary>
/// Allows for extending request processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
private void InterceptRequest(IRestRequest request)
{
lwaAuthorizationSigner.Sign(request);
awsSigV4Signer.Sign(request, RestClient.BaseUrl.Host);
}
/// <summary>
/// Allows for extending response processing for <see cref="ApiClient"/> generated code.
/// </summary>
/// <param name="request">The RestSharp request object</param>
/// <param name="response">The RestSharp response object</param>
partial void InterceptResponse(IRestRequest request, IRestResponse response);
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class
/// with default base path ({{{basePath}}}).
/// </summary>
/// <param name="config">An instance of Configuration.</param>
public ApiClient(Configuration config)
{
Configuration = config ?? {{packageName}}.Client.Configuration.Default;
RestClient = new RestClient(Configuration.BasePath);
{{#netStandard}}
RestClient.IgnoreResponseStatusCode = true;
{{/netStandard}}
lwaAuthorizationSigner = new LWAAuthorizationSigner(Configuration.AuthorizationCredentials);
if (Configuration.AuthenticationCredentialsProvider!=null)
{
awsSigV4Signer = new AWSSigV4Signer(configuration.AuthenticationCredentials, Configuration.AuthenticationCredentialsProvider);
}
else
{
awsSigV4Signer = new AWSSigV4Signer(Configuration.AuthenticationCredentials);
}
}
/// <summary>
/// Gets or sets the default API client for making HTTP calls.
/// </summary>
/// <value>The default API client.</value>
[Obsolete("ApiClient.Default is deprecated, please use 'Configuration.Default.ApiClient' instead.")]
public static ApiClient Default;
/// <summary>
/// Gets or sets an instance of the IReadableConfiguration.
/// </summary>
/// <value>An instance of the IReadableConfiguration.</value>
/// <remarks>
/// <see cref="IReadableConfiguration"/> helps us to avoid modifying possibly global
/// configuration values from within a given client. It does not guarantee thread-safety
/// of the <see cref="Configuration"/> instance in any way.
/// </remarks>
public IReadableConfiguration Configuration { get; set; }
/// <summary>
/// Gets or sets the RestClient.
/// </summary>
/// <value>An instance of the RestClient</value>
public RestClient RestClient { get; set; }
// Creates and sets up a RestRequest prior to a call.
private RestRequest PrepareRequest(
String path, {{^netStandard}}RestSharp.{{/netStandard}}Method method, List<KeyValuePair<String, String>> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = new RestRequest(path, method);
{{#netStandard}}
// disable ResetSharp.Portable built-in serialization
request.Serializer = null;
{{/netStandard}}
// add path parameter, if any
foreach(var param in pathParams)
request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment);
// add header parameter, if any
foreach(var param in headerParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(var param in queryParams)
request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any
foreach(var param in formParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach(var param in fileParams)
{
{{#netStandard}}
request.AddFile(param.Value);
{{/netStandard}}
{{^netStandard}}
{{^supportsUWP}}
request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
{{/supportsUWP}}
{{#supportsUWP}}
byte[] paramWriter = null;
param.Value.Writer = delegate (Stream stream) { paramWriter = ToByteArray(stream); };
request.AddFile(param.Value.Name, paramWriter, param.Value.FileName, param.Value.ContentType);
{{/supportsUWP}}
{{/netStandard}}
}
if (postBody != null) // http body (model or byte[]) parameter
{
{{#netStandard}}
request.AddParameter(new Parameter { Value = postBody, Type = ParameterType.RequestBody, ContentType = contentType });
{{/netStandard}}
{{^netStandard}}
request.AddParameter(contentType, postBody, ParameterType.RequestBody);
{{/netStandard}}
}
return request;
}
/// <summary>
/// Makes the HTTP request (Sync).
/// </summary>
/// <param name="path">URL path.</param>
/// <param name="method">HTTP method.</param>
/// <param name="queryParams">Query parameters.</param>
/// <param name="postBody">HTTP body (POST request).</param>
/// <param name="headerParams">Header parameters.</param>
/// <param name="formParams">Form parameters.</param>
/// <param name="fileParams">File parameters.</param>
/// <param name="pathParams">Path parameters.</param>
/// <param name="contentType">Content Type of the request</param>
/// <returns>Object</returns>
public Object CallApi(
String path, {{^netStandard}}RestSharp.{{/netStandard}}Method method, List<KeyValuePair<String, String>> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams,
pathParams, contentType);
// set timeout
{{#netStandard}}RestClient.Timeout = TimeSpan.FromMilliseconds(Configuration.Timeout);{{/netStandard}}
{{^netStandard}}RestClient.Timeout = Configuration.Timeout;{{/netStandard}}
// set user agent
RestClient.UserAgent = Configuration.UserAgent;
InterceptRequest(request);
{{#netStandard}}
var response = RestClient.Execute(request).Result;
{{/netStandard}}
{{^netStandard}}
{{^supportsUWP}}
var response = RestClient.Execute(request);
{{/supportsUWP}}
{{#supportsUWP}}
// Using async method to perform sync call (uwp-only)
var response = RestClient.ExecuteTaskAsync(request).Result;
{{/supportsUWP}}
{{/netStandard}}
InterceptResponse(request, response);
return (Object) response;
}
{{#supportsAsync}}
/// <summary>
/// Makes the asynchronous HTTP request.
/// </summary>
/// <param name="path">URL path.</param>
/// <param name="method">HTTP method.</param>
/// <param name="queryParams">Query parameters.</param>
/// <param name="postBody">HTTP body (POST request).</param>
/// <param name="headerParams">Header parameters.</param>
/// <param name="formParams">Form parameters.</param>
/// <param name="fileParams">File parameters.</param>
/// <param name="pathParams">Path parameters.</param>
/// <param name="contentType">Content type.</param>
/// <returns>The Task instance.</returns>
public async System.Threading.Tasks.Task<Object> CallApiAsync(
String path, {{^netStandard}}RestSharp.{{/netStandard}}Method method, List<KeyValuePair<String, String>> queryParams, Object postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, Dictionary<String, String> pathParams,
String contentType)
{
var request = PrepareRequest(
path, method, queryParams, postBody, headerParams, formParams, fileParams,
pathParams, contentType);
InterceptRequest(request);
var response = await RestClient.Execute{{^netStandard}}TaskAsync{{/netStandard}}(request);
InterceptResponse(request, response);
return (Object)response;
}{{/supportsAsync}}
/// <summary>
/// Escape string (url-encoded).
/// </summary>
/// <param name="str">String to be escaped.</param>
/// <returns>Escaped string.</returns>
public string EscapeString(string str)
{
return UrlEncode(str);
}
/// <summary>
/// Create FileParameter based on Stream.
/// </summary>
/// <param name="name">Parameter name.</param>
/// <param name="stream">Input stream.</param>
/// <returns>FileParameter.</returns>
public FileParameter ParameterToFile(string name, Stream stream)
{
if (stream is FileStream)
return FileParameter.Create(name, ReadAsBytes(stream), Path.GetFileName(((FileStream)stream).Name));
else
return FileParameter.Create(name, ReadAsBytes(stream), "no_file_name_provided");
}
/// <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>
/// <returns>Formatted string.</returns>
public string ParameterToString(object obj)
{
if (obj is 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)obj).ToString (Configuration.DateTimeFormat);
else if (obj is 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)obj).ToString (Configuration.DateTimeFormat);
else if (obj is IList)
{
var flattenedString = new StringBuilder();
foreach (var param in (IList)obj)
{
if (flattenedString.Length > 0)
flattenedString.Append(",");
flattenedString.Append(param);
}
return flattenedString.ToString();
}
else
return Convert.ToString (obj);
}
/// <summary>
/// Deserialize the JSON string into a proper object.
/// </summary>
/// <param name="response">The HTTP response.</param>
/// <param name="type">Object type.</param>
/// <returns>Object representation of the JSON string.</returns>
public object Deserialize(IRestResponse response, Type type)
{
{{^netStandard}}IList<Parameter>{{/netStandard}}{{#netStandard}}IHttpHeaders{{/netStandard}} headers = response.Headers;
if (type == typeof(byte[])) // return byte array
{
return response.RawBytes;
}
// TODO: ? if (type.IsAssignableFrom(typeof(Stream)))
if (type == typeof(Stream))
{
if (headers != null)
{
var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath)
? Path.GetTempPath()
: Configuration.TempFolderPath;
var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$");
foreach (var header in headers)
{
var match = regex.Match(header.ToString());
if (match.Success)
{
string fileName = filePath + SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", ""));
File.WriteAllBytes(fileName, response.RawBytes);
return new FileStream(fileName, FileMode.Open);
}
}
}
var stream = new MemoryStream(response.RawBytes);
return stream;
}
if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
{
return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind);
}
if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type
{
return ConvertType(response.Content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(response.Content, type, serializerSettings);
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Serialize an input (model) into JSON string
/// </summary>
/// <param name="obj">Object.</param>
/// <returns>JSON string.</returns>
public String Serialize(object obj)
{
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
/// <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 bool IsJsonMime(String mime)
{
var jsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$");
return mime != null && (jsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"));
}
/// <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 String SelectHeaderContentType(String[] contentTypes)
{
if (contentTypes.Length == 0)
return "application/json";
foreach (var contentType in contentTypes)
{
if (IsJsonMime(contentType.ToLower()))
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 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>
/// 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 System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text));
}
/// <summary>
/// Dynamically cast the object into target type.
/// </summary>
/// <param name="fromObject">Object to be casted</param>
/// <param name="toObject">Target type</param>
/// <returns>Casted object</returns>
{{#supportsAsync}}
public static dynamic ConvertType(dynamic fromObject, Type toObject)
{{/supportsAsync}}
{{^supportsAsync}}
public static object ConvertType<T>(T fromObject, Type toObject) where T : class
{{/supportsAsync}}
{
return Convert.ChangeType(fromObject, toObject);
}
/// <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)
{
byte[] buf = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int count;
while ((count = inputStream.Read(buf, 0, buf.Length)) > 0)
{
ms.Write(buf, 0, count);
}
return ms.ToArray();
}
}
/// <summary>
/// URL encode a string
/// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50
/// </summary>
/// <param name="input">String to be URL encoded</param>
/// <returns>Byte array</returns>
public static string UrlEncode(string input)
{
const int maxLength = 32766;
if (input == null)
{
throw new ArgumentNullException("input");
}
if (input.Length <= maxLength)
{
return Uri.EscapeDataString(input);
}
StringBuilder sb = new StringBuilder(input.Length * 2);
int index = 0;
while (index < input.Length)
{
int length = Math.Min(input.Length - index, maxLength);
string subString = input.Substring(index, length);
sb.Append(Uri.EscapeDataString(subString));
index += subString.Length;
}
return sb.ToString();
}
/// <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, @".*[/\\](.*)$");
if (match.Success)
{
return match.Groups[1].Value;
}
else
{
return filename;
}
}
{{^netStandard}}
{{#supportsUWP}}
/// <summary>
/// Convert stream to byte array
/// </summary>
/// <param name="stream">IO stream</param>
/// <returns>Byte array</returns>
public static byte[] ToByteArray(Stream stream)
{
stream.Position = 0;
byte[] buffer = new byte[stream.Length];
for (int totalBytesCopied = 0; totalBytesCopied < stream.Length;)
totalBytesCopied += stream.Read(buffer, totalBytesCopied, Convert.ToInt32(stream.Length) - totalBytesCopied);
return buffer;
}
{{/supportsUWP}}
{{/netStandard}}
/// <summary>
/// Convert params to key/value pairs.
/// Use collectionFormat to properly format lists and collections.
/// </summary>
/// <param name="name">Key name.</param>
/// <param name="value">Value object.</param>
/// <returns>A list of KeyValuePairs</returns>
public IEnumerable<KeyValuePair<string, string>> ParameterToKeyValuePairs(string collectionFormat, string name, object value)
{
var parameters = new List<KeyValuePair<string, string>>();
if (IsCollection(value) && collectionFormat == "multi")
{
var valueCollection = value as IEnumerable;
parameters.AddRange(from object item in valueCollection select new KeyValuePair<string, string>(name, ParameterToString(item)));
}
else
{
parameters.Add(new KeyValuePair<string, string>(name, ParameterToString(value)));
}
return parameters;
}
/// <summary>
/// Check if generic object is a collection.
/// </summary>
/// <param name="value"></param>
/// <returns>True if object is a collection type</returns>
private static bool IsCollection(object value)
{
return value is IList || value is ICollection;
}
}
}