docUtillTs.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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 DocUtilTs {
  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${DocUtilTs.firstUpper(objKey)}`;
  39. let entityName = DocUtilTs.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. contentType: apis.contentType
  80. });
  81. }
  82. }
  83. }
  84. fs.writeFileSync(this.info.filePath + "/" + this.info.fileName + ".ts", this.buildContent());
  85. }
  86. // enum StatusCode {
  87. // @JsonValue(200)
  88. // success,
  89. // @JsonValue('500')
  90. // weird,
  91. // }
  92. public buildContent() {
  93. return `
  94. import RequestUtil, { AxiosRequestConfigFunc } from "@/utils/request";
  95. ${this.entity}
  96. export default class ${this.info.name} {
  97. ${this.funcs}
  98. }
  99. `
  100. };
  101. public mapType(type: any): string {
  102. let obj: any = {
  103. String: "string",
  104. int: "number",
  105. double: "number"
  106. }
  107. return obj[type];
  108. }
  109. public funcTemple(obj: {
  110. name: string,
  111. desc?: string,
  112. method: string,
  113. url: string,
  114. body: string | false,
  115. params: string | false,
  116. response: string | false,
  117. responseList: boolean,
  118. responsecomplex: boolean,
  119. element: IApiDocFuncInterface,
  120. contentType?: "json" | "urlencoded" | "formData"
  121. }) {
  122. let serialize = "";
  123. let _response = obj.response || "any";
  124. if (obj.response) {
  125. if (obj.responseList) {
  126. _response = `${obj.response}[]`;
  127. }
  128. if (obj.responsecomplex) {
  129. if (obj.responseList) {
  130. serialize = `, serialize: (data)=> [for (var i in data) ${obj.response}.fromJson(i)]`;
  131. } else {
  132. serialize = `, serialize: (data)=> ${obj.response}.fromJson(data)`;
  133. }
  134. }
  135. else {
  136. serialize = `,serialize:(dynamic data)=>data`
  137. }
  138. }
  139. let url = obj.url;
  140. if (obj.element.params) {
  141. for (const key in obj.element.params) {
  142. const element = obj.element.params[key];
  143. if (element.url === true) {
  144. url = url.replace(`{${key}}`, `\${options.params!.${key}}`);
  145. }
  146. }
  147. }
  148. return (
  149. `
  150. /// ${obj.desc}
  151. static ${obj.name}(options:AxiosRequestConfigFunc<${obj.body || "any"},${obj.params || "any"}> ):RequestUtil<${_response || "any"}> {
  152. return new RequestUtil<${_response || "any"}>(\`${url}\`,'${obj.method.toUpperCase()}' ,options);
  153. }
  154. `
  155. )
  156. };
  157. public enumTemple(name: string, params: Record<string, number | string>) {
  158. let _list: string[] = []
  159. for (const key in params) {
  160. const element = params[key];
  161. let _element = typeof element === "string" ? `"${element}"` : element;
  162. _list.push(`@JsonValue(${_element})`);
  163. _list.push(DocUtilTs.lowerCamelCase(element.toString()) + ",");
  164. }
  165. this.entity +=
  166. `
  167. export enum ${DocUtilTs.firstUpper(name)} {
  168. ${_list.join("\r\n")}
  169. }
  170. `
  171. }
  172. public paramsTemple(name: string, params: Record<string, IParamsType>) {
  173. let str = "";
  174. let iniStr: string[] = [];
  175. for (const key in params) {
  176. const element = params[key];
  177. let jsonKey = element.jsonKey ? `@JsonKey(name: "${element.jsonKey}")` : "";
  178. let _final = element.final != false ? "" : "";
  179. if (element.type === "object" && element.child && typeof element.child !== "string") {
  180. this.paramsTemple(name + DocUtilTs.firstUpper(key), element.child);
  181. str += `
  182. /// ${element.desc}
  183. ${_final} ${key}${element.required != false ? "!" : "?"}: ${name + DocUtilTs.firstUpper(key)} ;
  184. `
  185. iniStr.push(` ${element.required != false ? "required" : ""} this.${key}`);
  186. }
  187. else if (element.type === "enum") {
  188. if (element.enum) {
  189. this.enumTemple(name + DocUtilTs.firstUpper(key), element.enum);
  190. str += `
  191. /// ${element.desc}
  192. ${_final} ${key}${element.required != false ? "!" : "?"}: ${name + DocUtilTs.firstUpper(key)};
  193. `
  194. iniStr.push(` ${element.required != false ? "required" : ""} this.${key}`);
  195. }
  196. }
  197. else if (element.type === "list" && element.child) {
  198. let _type = "";
  199. if (typeof element.child !== "string") {
  200. this.paramsTemple(name + DocUtilTs.firstUpper(key), element.child);
  201. _type = name + DocUtilTs.firstUpper(key);
  202. }
  203. else {
  204. _type = element.child;
  205. }
  206. str += `
  207. /// ${element.desc}
  208. ${_final} ${key}${element.required != false ? "!" : "?"}: ${_type}[] ;
  209. `
  210. iniStr.push(` ${element.required != false ? "required" : ""} this.${key}`);
  211. }
  212. else {
  213. str += `
  214. /// ${element.desc}
  215. ${_final} ${key}${element.required != false ? "!" : "?"}: ${this.mapType(element.type)} ;
  216. `
  217. iniStr.push(` ${element.required != false ? "required" : ""} this.${key}`);
  218. }
  219. }
  220. this.entity += `
  221. export class ${name} {
  222. ${str}
  223. }
  224. `
  225. return true;
  226. }
  227. }