This repository has been archived by the owner on Jan 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_client.dart
executable file
·153 lines (132 loc) · 5.2 KB
/
api_client.dart
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
part of swagger.api;
class QueryParam {
String name;
String value;
QueryParam(this.name, this.value);
}
class ApiClient {
String basePath;
var client = new BrowserClient();
Map<String, String> _defaultHeaderMap = {};
Map<String, Authentication> _authentications = {};
final dson = new Dartson.JSON()
..addTransformer(new DateTimeParser(), DateTime);
final _RegList = new RegExp(r'^List<(.*)>$');
final _RegMap = new RegExp(r'^Map<String,(.*)>$');
ApiClient({this.basePath: "https://api.steemjs.com"}) {
// Setup authentications (key: authentication name, value: authentication).
}
void addDefaultHeader(String key, String value) {
_defaultHeaderMap[key] = value;
}
dynamic _deserialize(dynamic value, String targetType) {
try {
switch (targetType) {
case 'String':
return '$value';
case 'int':
return value is int ? value : int.parse('$value');
case 'bool':
return value is bool ? value : '$value'.toLowerCase() == 'true';
case 'double':
return value is double ? value : double.parse('$value');
case 'Accounts':
return dson.map(value, new Accounts());
case 'Error':
return dson.map(value, new Error());
case 'GetAccountCount':
return dson.map(value, new GetAccountCount());
case 'GetVersion':
return dson.map(value, new GetVersion());
case '_':
return dson.map(value, new _());
default:
{
Match match;
if (value is List &&
(match = _RegList.firstMatch(targetType)) != null) {
var newTargetType = match[1];
return value.map((v) => _deserialize(v, newTargetType)).toList();
} else if (value is Map &&
(match = _RegMap.firstMatch(targetType)) != null) {
var newTargetType = match[1];
return new Map.fromIterables(value.keys,
value.values.map((v) => _deserialize(v, newTargetType)));
}
}
}
} catch (e, stack) {
throw new ApiException.withInner(500, 'Exception during deserialization.', e, stack);
}
throw new ApiException(500, 'Could not find a suitable class for deserialization');
}
dynamic deserialize(String json, String targetType) {
// Remove all spaces. Necessary for reg expressions as well.
targetType = targetType.replaceAll(' ', '');
if (targetType == 'String') return json;
var decodedJson = JSON.decode(json);
return _deserialize(decodedJson, targetType);
}
String serialize(Object obj) {
String serialized = '';
if (obj == null) {
serialized = '';
} else if (obj is String) {
serialized = obj;
} else {
serialized = dson.encode(obj);
}
return serialized;
}
// We don't use a Map<String, String> for queryParams.
// If collectionFormat is 'multi' a key might appear multiple times.
Future<Response> invokeAPI(String path,
String method,
Iterable<QueryParam> queryParams,
Object body,
Map<String, String> headerParams,
Map<String, String> formParams,
String contentType,
List<String> authNames) async {
_updateParamsForAuth(authNames, queryParams, headerParams);
var ps = queryParams.where((p) => p.value != null).map((p) => '${p.name}=${p.value}');
String queryString = ps.isNotEmpty ?
'?' + ps.join('&') :
'';
String url = basePath + path + queryString;
headerParams.addAll(_defaultHeaderMap);
headerParams['Content-Type'] = contentType;
if(body is MultipartRequest) {
var request = new MultipartRequest(method, Uri.parse(url));
request.fields.addAll(body.fields);
request.files.addAll(body.files);
request.headers.addAll(body.headers);
request.headers.addAll(headerParams);
var response = await client.send(request);
return Response.fromStream(response);
} else {
var msgBody = contentType == "application/x-www-form-urlencoded" ? formParams : serialize(body);
switch(method) {
case "POST":
return client.post(url, headers: headerParams, body: msgBody);
case "PUT":
return client.put(url, headers: headerParams, body: msgBody);
case "DELETE":
return client.delete(url, headers: headerParams);
case "PATCH":
return client.patch(url, headers: headerParams, body: msgBody);
default:
return client.get(url, headers: headerParams);
}
}
}
/// Update query and header parameters based on authentication settings.
/// @param authNames The authentications to apply
void _updateParamsForAuth(List<String> authNames, List<QueryParam> queryParams, Map<String, String> headerParams) {
authNames.forEach((authName) {
Authentication auth = _authentications[authName];
if (auth == null) throw new ArgumentError("Authentication undefined: " + authName);
auth.applyToParams(queryParams, headerParams);
});
}
}