vars.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. package dartgen
  2. import "text/template"
  3. var funcMap = template.FuncMap{
  4. "getBaseName": getBaseName,
  5. "getPropertyFromMember": getPropertyFromMember,
  6. "isDirectType": isDirectType,
  7. "isNumberType": isNumberType,
  8. "isClassListType": isClassListType,
  9. "isListItemsNullable": isListItemsNullable,
  10. "isNullableType": isNullableType,
  11. "appendNullCoalescing": appendNullCoalescing,
  12. "appendDefaultEmptyValue": appendDefaultEmptyValue,
  13. "getCoreType": getCoreType,
  14. "lowCamelCase": lowCamelCase,
  15. "normalizeHandlerName": normalizeHandlerName,
  16. "hasUrlPathParams": hasUrlPathParams,
  17. "extractPositionalParamsFromPath": extractPositionalParamsFromPath,
  18. "makeDartRequestUrlPath": makeDartRequestUrlPath,
  19. }
  20. const (
  21. apiFileContent = `import 'dart:io';
  22. import 'dart:convert';
  23. import '../vars/kv.dart';
  24. import '../vars/vars.dart';
  25. /// 发送POST请求.
  26. ///
  27. /// data:为你要post的结构体,我们会帮你转换成json字符串;
  28. /// ok函数:请求成功的时候调用,fail函数:请求失败的时候会调用,eventually函数:无论成功失败都会调用
  29. Future apiPost(String path, dynamic data,
  30. {Map<String, String> header,
  31. Function(Map<String, dynamic>) ok,
  32. Function(String) fail,
  33. Function eventually}) async {
  34. await _apiRequest('POST', path, data,
  35. header: header, ok: ok, fail: fail, eventually: eventually);
  36. }
  37. /// 发送GET请求.
  38. ///
  39. /// ok函数:请求成功的时候调用,fail函数:请求失败的时候会调用,eventually函数:无论成功失败都会调用
  40. Future apiGet(String path,
  41. {Map<String, String> header,
  42. Function(Map<String, dynamic>) ok,
  43. Function(String) fail,
  44. Function eventually}) async {
  45. await _apiRequest('GET', path, null,
  46. header: header, ok: ok, fail: fail, eventually: eventually);
  47. }
  48. Future _apiRequest(String method, String path, dynamic data,
  49. {Map<String, String> header,
  50. Function(Map<String, dynamic>) ok,
  51. Function(String) fail,
  52. Function eventually}) async {
  53. var tokens = await getTokens();
  54. try {
  55. var client = HttpClient();
  56. HttpClientRequest r;
  57. if (method == 'POST') {
  58. r = await client.postUrl(Uri.parse(serverHost + path));
  59. } else {
  60. r = await client.getUrl(Uri.parse(serverHost + path));
  61. }
  62. var strData = '';
  63. if (data != null) {
  64. strData = jsonEncode(data);
  65. }
  66. if (method == 'POST') {
  67. r.headers.set('Content-Type', 'application/json; charset=utf-8');
  68. r.headers.set('Content-Length', utf8.encode(strData).length);
  69. }
  70. if (tokens != null) {
  71. r.headers.set('Authorization', tokens.accessToken);
  72. }
  73. if (header != null) {
  74. header.forEach((k, v) {
  75. r.headers.set(k, v);
  76. });
  77. }
  78. r.write(strData);
  79. var rp = await r.close();
  80. var body = await rp.transform(utf8.decoder).join();
  81. print('${rp.statusCode} - $path');
  82. print('-- request --');
  83. print(strData);
  84. print('-- response --');
  85. print('$body \n');
  86. if (rp.statusCode == 404) {
  87. if (fail != null) fail('404 not found');
  88. } else {
  89. Map<String, dynamic> base = jsonDecode(body);
  90. if (rp.statusCode == 200) {
  91. if (base['code'] != 0) {
  92. if (fail != null) fail(base['desc']);
  93. } else {
  94. if (ok != null) ok(base['data']);
  95. }
  96. } else if (base['code'] != 0) {
  97. if (fail != null) fail(base['desc']);
  98. }
  99. }
  100. } catch (e) {
  101. if (fail != null) fail(e.toString());
  102. }
  103. if (eventually != null) eventually();
  104. }
  105. `
  106. apiFileContentV2 = `import 'dart:io';
  107. import 'dart:convert';
  108. import '../vars/kv.dart';
  109. import '../vars/vars.dart';
  110. /// send request with post method
  111. ///
  112. /// data: any request class that will be converted to json automatically
  113. /// ok: is called when request succeeds
  114. /// fail: is called when request fails
  115. /// eventually: is always called until the nearby functions returns
  116. Future apiPost(String path, dynamic data,
  117. {Map<String, String>? header,
  118. Function(Map<String, dynamic>)? ok,
  119. Function(String)? fail,
  120. Function? eventually}) async {
  121. await _apiRequest('POST', path, data,
  122. header: header, ok: ok, fail: fail, eventually: eventually);
  123. }
  124. /// send request with get method
  125. ///
  126. /// ok: is called when request succeeds
  127. /// fail: is called when request fails
  128. /// eventually: is always called until the nearby functions returns
  129. Future apiGet(String path,
  130. {Map<String, String>? header,
  131. Function(Map<String, dynamic>)? ok,
  132. Function(String)? fail,
  133. Function? eventually}) async {
  134. await _apiRequest('GET', path, null,
  135. header: header, ok: ok, fail: fail, eventually: eventually);
  136. }
  137. Future _apiRequest(String method, String path, dynamic data,
  138. {Map<String, String>? header,
  139. Function(Map<String, dynamic>)? ok,
  140. Function(String)? fail,
  141. Function? eventually}) async {
  142. var tokens = await getTokens();
  143. try {
  144. var client = HttpClient();
  145. HttpClientRequest r;
  146. if (method == 'POST') {
  147. r = await client.postUrl(Uri.parse(serverHost + path));
  148. } else {
  149. r = await client.getUrl(Uri.parse(serverHost + path));
  150. }
  151. var strData = '';
  152. if (data != null) {
  153. strData = jsonEncode(data);
  154. }
  155. if (method == 'POST') {
  156. r.headers.set('Content-Type', 'application/json; charset=utf-8');
  157. r.headers.set('Content-Length', utf8.encode(strData).length);
  158. }
  159. if (tokens != null) {
  160. r.headers.set('Authorization', tokens.accessToken);
  161. }
  162. if (header != null) {
  163. header.forEach((k, v) {
  164. r.headers.set(k, v);
  165. });
  166. }
  167. r.write(strData);
  168. var rp = await r.close();
  169. var body = await rp.transform(utf8.decoder).join();
  170. print('${rp.statusCode} - $path');
  171. print('-- request --');
  172. print(strData);
  173. print('-- response --');
  174. print('$body \n');
  175. if (rp.statusCode == 404) {
  176. if (fail != null) fail('404 not found');
  177. } else {
  178. Map<String, dynamic> base = jsonDecode(body);
  179. if (rp.statusCode == 200) {
  180. if (base['code'] != 0) {
  181. if (fail != null) fail(base['desc']);
  182. } else {
  183. if (ok != null) ok(base['data']);
  184. }
  185. } else if (base['code'] != 0) {
  186. if (fail != null) fail(base['desc']);
  187. }
  188. }
  189. } catch (e) {
  190. if (fail != null) fail(e.toString());
  191. }
  192. if (eventually != null) eventually();
  193. }`
  194. tokensFileContent = `class Tokens {
  195. /// 用于访问的token, 每次请求都必须带在Header里面
  196. final String accessToken;
  197. final int accessExpire;
  198. /// 用于刷新token
  199. final String refreshToken;
  200. final int refreshExpire;
  201. final int refreshAfter;
  202. Tokens(
  203. {this.accessToken,
  204. this.accessExpire,
  205. this.refreshToken,
  206. this.refreshExpire,
  207. this.refreshAfter});
  208. factory Tokens.fromJson(Map<String, dynamic> m) {
  209. return Tokens(
  210. accessToken: m['access_token'],
  211. accessExpire: m['access_expire'],
  212. refreshToken: m['refresh_token'],
  213. refreshExpire: m['refresh_expire'],
  214. refreshAfter: m['refresh_after']);
  215. }
  216. Map<String, dynamic> toJson() {
  217. return {
  218. 'access_token': accessToken,
  219. 'access_expire': accessExpire,
  220. 'refresh_token': refreshToken,
  221. 'refresh_expire': refreshExpire,
  222. 'refresh_after': refreshAfter,
  223. };
  224. }
  225. }
  226. `
  227. tokensFileContentV2 = `class Tokens {
  228. /// 用于访问的token, 每次请求都必须带在Header里面
  229. final String accessToken;
  230. final int accessExpire;
  231. /// 用于刷新token
  232. final String refreshToken;
  233. final int refreshExpire;
  234. final int refreshAfter;
  235. Tokens({
  236. required this.accessToken,
  237. required this.accessExpire,
  238. required this.refreshToken,
  239. required this.refreshExpire,
  240. required this.refreshAfter
  241. });
  242. factory Tokens.fromJson(Map<String, dynamic> m) {
  243. return Tokens(
  244. accessToken: m['access_token'],
  245. accessExpire: m['access_expire'],
  246. refreshToken: m['refresh_token'],
  247. refreshExpire: m['refresh_expire'],
  248. refreshAfter: m['refresh_after']);
  249. }
  250. Map<String, dynamic> toJson() {
  251. return {
  252. 'access_token': accessToken,
  253. 'access_expire': accessExpire,
  254. 'refresh_token': refreshToken,
  255. 'refresh_expire': refreshExpire,
  256. 'refresh_after': refreshAfter,
  257. };
  258. }
  259. }
  260. `
  261. )