docUtill.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. import fs from 'fs';
  2. import { IApiDocFuncInterface, IParamsType } from "../base/interface";
  3. import ApiGenerateImpl from "../interface/api_generate_impl";
  4. import { execSync } from 'child_process';
  5. export default class DocUtil {
  6. static runner(app: string) {
  7. execSync("cd ../" + app + " && flutter pub run build_runner build ");
  8. }
  9. static firstUpper(name: string) {
  10. let nameSpilit = name.split("");
  11. nameSpilit[0] = name[0].toUpperCase();
  12. return nameSpilit.join("");
  13. }
  14. static lowerCamelCase(name: string) {
  15. let nameSpilit = name.split("_");
  16. if (nameSpilit.length > 1) {
  17. nameSpilit.forEach((p, i) => {
  18. if (i > 0) {
  19. nameSpilit[i] = this.firstUpper(nameSpilit[i]);
  20. }
  21. })
  22. }
  23. return nameSpilit.join("");
  24. // nameSpilit[0] = name[0].toUpperCase();
  25. // return nameSpilit.join("");
  26. }
  27. public info: ApiGenerateImpl;
  28. public entity: string = "";
  29. public funcs: string = "";
  30. constructor(_info: ApiGenerateImpl) {
  31. this.info = _info;
  32. let api = this.info.doc;
  33. for (const key in api) {
  34. const apis = api[key];
  35. for (const objKey in apis) {
  36. const element = (apis as any)[objKey] as IApiDocFuncInterface;
  37. if (['post', 'put', 'get', 'delete'].includes(objKey)) {
  38. let name = `${apis.funcName}Using${DocUtil.firstUpper(objKey)}`;
  39. let entityName = DocUtil.firstUpper(name);
  40. let body = !!element.body && this.paramsTemple(`${entityName}Body`, element.body) && `${entityName}Body`;
  41. let params = !!element.params && this.paramsTemple(`${entityName}Params`, element.params) && `${entityName}Params`;
  42. let response: string | false = false;
  43. let responseList = false;
  44. /// 是否复杂的返回值-需要反序列化
  45. let responsecomplex = false;
  46. if (element.response) {
  47. if (typeof element.response === "string") {
  48. response = element.response;
  49. }
  50. else if (Array.isArray(element.response)) {
  51. responseList = true;
  52. // response = `List<${element.}>`;
  53. let _type = element.response[0];
  54. if (typeof _type === "string") {
  55. response = _type;
  56. }
  57. else {
  58. responsecomplex = true;
  59. response = this.paramsTemple(`${entityName}Response`, _type) && `${entityName}Response`;
  60. }
  61. }
  62. else {
  63. responsecomplex = true;
  64. response = this.paramsTemple(`${entityName}Response`, element.response) && `${entityName}Response`;
  65. }
  66. }
  67. // let response = !!element.response && ((typeof element.response === "string") ? element.response : this.paramsTemple(`${entityName}Response`, element.response) && `${entityName}Response`);
  68. this.funcs += this.funcTemple({
  69. desc: apis.desc,
  70. name,
  71. method: objKey,
  72. url: key,
  73. body,
  74. params,
  75. response,
  76. responseList,
  77. responsecomplex,
  78. element
  79. });
  80. }
  81. }
  82. }
  83. fs.writeFileSync(this.info.filePath + "/" + this.info.fileName + ".dart", this.buildContent());
  84. }
  85. // enum StatusCode {
  86. // @JsonValue(200)
  87. // success,
  88. // @JsonValue('500')
  89. // weird,
  90. // }
  91. public buildContent() {
  92. return `
  93. import 'package:dio/dio.dart';
  94. import 'package:dc/utils/request_util.dart';
  95. import 'package:json_annotation/json_annotation.dart';
  96. part '${this.info.fileName + ".g.dart"}';
  97. ${this.entity}
  98. class ${this.info.name} {
  99. ${this.funcs}
  100. }
  101. `
  102. };
  103. public funcTemple(obj: {
  104. name: string,
  105. desc?: string,
  106. method: string,
  107. url: string,
  108. body: string | false,
  109. params: string | false,
  110. response: string | false,
  111. responseList: boolean,
  112. responsecomplex: boolean,
  113. element: IApiDocFuncInterface
  114. }) {
  115. let serialize = "";
  116. let _response = obj.response || "dynamic";
  117. if (obj.response) {
  118. if (obj.responseList) {
  119. _response = `List<${obj.response}>`;
  120. }
  121. if (obj.responsecomplex) {
  122. if (obj.responseList) {
  123. serialize = `, serialize: (data)=> [for (var i in data) ${obj.response}.fromJson(i)]`;
  124. } else {
  125. serialize = `, serialize: (data)=> ${obj.response}.fromJson(data)`;
  126. }
  127. }
  128. else {
  129. serialize = `,serialize:(dynamic data)=>data`
  130. }
  131. }
  132. let url = obj.url;
  133. if (obj.element.params) {
  134. for (const key in obj.element.params) {
  135. const element = obj.element.params[key];
  136. if (element.url === true) {
  137. url = url.replace(`{${key}}`, `\${params.${key}}`);
  138. }
  139. }
  140. }
  141. return (
  142. `
  143. /// ${obj.desc}
  144. static RequestUtil<${_response || "dynamic"}> ${obj.name}({${obj.body ? "required" : ""} ${obj.body || "dynamic"} body,${obj.params ? "required" : ""} ${obj.params || "dynamic"} params, bool showLoading = false, bool tips = false, bool errorTips = false, bool successTips = false, Options? options, Function(int, int)? onSendProgress,}) {
  145. return RequestUtil<${_response || "dynamic"}>('${url}', RequestMethod.${obj.method}, body: body${obj.body ? ".toJson()" : ""}, params: params${obj.params ? ".toJson()" : ""}, showLoading: showLoading, tips: tips, errorTips: errorTips, successTips: successTips, options: options,onSendProgress:onSendProgress${serialize},);
  146. }
  147. `
  148. )
  149. };
  150. public enumTemple(name: string, params: Record<string, number | string>) {
  151. let _list: string[] = []
  152. for (const key in params) {
  153. const element = params[key];
  154. let _element = typeof element === "string" ? `"${element}"` : element;
  155. _list.push(`@JsonValue(${_element})`);
  156. _list.push(DocUtil.lowerCamelCase(element.toString()) + ",");
  157. }
  158. this.entity +=
  159. `
  160. enum ${DocUtil.firstUpper(name)} {
  161. ${_list.join("\r\n")}
  162. }
  163. `
  164. }
  165. public paramsTemple(name: string, params: Record<string, IParamsType>) {
  166. let str = "";
  167. let iniStr: string[] = [];
  168. for (const key in params) {
  169. const element = params[key];
  170. let jsonKey = element.jsonKey ? `@JsonKey(name: "${element.jsonKey}")` : "";
  171. let _final = element.final != false ? "final " : "";
  172. if (element.type === "object" && element.child && typeof element.child !== "string") {
  173. this.paramsTemple(name + DocUtil.firstUpper(key), element.child);
  174. str += `
  175. /// ${element.desc}
  176. ${jsonKey}
  177. ${_final} ${name + DocUtil.firstUpper(key)}${element.required != false ? "" : "?"} ${key};
  178. `
  179. iniStr.push(` ${element.required != false ? "required" : ""} this.${key}`);
  180. }
  181. else if (element.type === "enum") {
  182. if (element.enum) {
  183. this.enumTemple(name + DocUtil.firstUpper(key), element.enum);
  184. str += `
  185. /// ${element.desc}
  186. ${jsonKey}
  187. ${_final} ${name + DocUtil.firstUpper(key)}${element.required != false ? "" : "?"} ${key};
  188. `
  189. iniStr.push(` ${element.required != false ? "required" : ""} this.${key}`);
  190. }
  191. }
  192. else if (element.type === "list" && element.child) {
  193. let _type = "";
  194. if (typeof element.child !== "string") {
  195. this.paramsTemple(name + DocUtil.firstUpper(key), element.child);
  196. _type = name + DocUtil.firstUpper(key);
  197. }
  198. else {
  199. _type = element.child;
  200. }
  201. str += `
  202. /// ${element.desc}
  203. ${jsonKey}
  204. ${_final} List<${_type}>${element.required != false ? "" : "?"} ${key};
  205. `
  206. iniStr.push(` ${element.required != false ? "required" : ""} this.${key}`);
  207. }
  208. else {
  209. str += `
  210. /// ${element.desc}
  211. ${jsonKey}
  212. ${_final} ${element.type}${element.required != false ? "" : "?"} ${key};
  213. `
  214. iniStr.push(` ${element.required != false ? "required" : ""} this.${key}`);
  215. }
  216. }
  217. this.entity += `
  218. @JsonSerializable()
  219. class ${name} {
  220. ${str}
  221. ${name}({${iniStr.join(", ")}});
  222. factory ${name}.fromJson(Map<String, dynamic> json) => _$${name}FromJson(json);
  223. Map<String, dynamic> toJson() => _$${name}ToJson(this);
  224. }
  225. `
  226. return true;
  227. }
  228. }