getInterFace.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. /* eslint-disable import/extensions */
  2. /* eslint-disable @typescript-eslint/no-var-requires */
  3. const common = require('./common.js')
  4. const { cl, request, files } = common
  5. const convert = {
  6. /** 特殊替换时使用 */
  7. _placeholder: '_',
  8. _maps: {
  9. baseTypes: ['integer', 'int', 'long', 'bigdecimal', 'string'],
  10. /** 需要替换的类型 */
  11. dataTypes: {
  12. number: ['integer', 'int', 'long', 'bigdecimal'],
  13. Array: ['Collection', 'List'],
  14. Record: ['Map'],
  15. IPage: ['Page'],
  16. IPageParams: ['分页请求参数'],
  17. AnyObject: ['object', 'JSONObject'],
  18. },
  19. scheamas: {},
  20. /** 完整替换的类型 */
  21. completes: Object.entries({
  22. 'Array<any>': ['array'],
  23. any: ['Result', '返回值'],
  24. 'Record<any, any>': ['Record', 'Map'],
  25. 'IPageParams<any>': ['IPageParams'],
  26. }),
  27. },
  28. /** 修正被占位符替换破坏的类型修饰 */
  29. correct(str) {
  30. /** 修正被替换的基础类型后面的, */
  31. convert._maps.baseTypes.forEach((f) => {
  32. const cs = `${f}${convert._placeholder}`
  33. if (str.includes(cs)) {
  34. str = str.replace(cs, `${f}, `)
  35. }
  36. })
  37. return str
  38. },
  39. /** 转换类型定义 */
  40. definitions(str) {
  41. str = str.replace('#/definitions/', '')
  42. str = convert.getSafeStr(str)
  43. str = convert.correct(str)
  44. str = convert.dataTypesMap(str, 1)
  45. str = str.replace(/«/g, '<')
  46. str = str.replace(/»/g, '>')
  47. for (const [k, v] of convert._maps.completes) {
  48. v.forEach((f) => {
  49. if (str === f) {
  50. str = k
  51. }
  52. })
  53. }
  54. return str
  55. // ms = ['返回值','List','Ipage']
  56. // str = '返回值«IPage«UserAccount对象»»'
  57. // function ffff(str) {
  58. // const rg = new RegExp(`([${ms.join('|')}])«(.+)»`)
  59. // const strm = str.match(rg)
  60. // if (strm && strm.length == 3) {
  61. // switch (strm[1]) {
  62. // case 'List':
  63. // str = `${strm[2]}[]`
  64. // defa
  65. // }
  66. // ffff(strm[2])
  67. // console.log(strm)
  68. // }
  69. // }
  70. },
  71. /** 类型替换
  72. * type 0:字符串完全替换,1:正则替换
  73. */
  74. dataTypesMap(str, type = 0) {
  75. if (!str) return ''
  76. for (const [k, v] of Object.entries(this._maps.dataTypes)) {
  77. v.forEach((f) => {
  78. if (type === 0) {
  79. str = str.replace(f, k)
  80. }
  81. if (type === 1) {
  82. // 脱壳
  83. str = str.replace(/^返回值«(.+)»/, '$1')
  84. str = str.replace(/^Result«(.+)»/, '$1')
  85. // 取出被«»包裹的类型
  86. const rg = new RegExp(`(^|«+)${f}([,«»]+|$)`)
  87. if (rg.test(str)) {
  88. // 替换这种类型
  89. str = str.replace(rg, `$1${k}$2`)
  90. // // 被特殊替换了的, 替换回来
  91. // const srp = `${k}${convert._placeholder}`
  92. // if (str.includes(srp)) {
  93. // str = str.replace(srp, `${k}, `)
  94. // }
  95. }
  96. }
  97. })
  98. }
  99. return str
  100. },
  101. _dirtyChars: ['-', ',', '、', '/', '(', ')', ','],
  102. getSafeStr(str) {
  103. this._dirtyChars.forEach((f) => {
  104. str = str.replaceAll(f, convert._placeholder)
  105. })
  106. return str
  107. },
  108. main({ name, url, basePath }) {
  109. basePath = basePath.replace(/^\//, '')
  110. return request
  111. .get(url)
  112. .then((res) => {
  113. // const tt = files.getIFPath(basePath + '_raw')
  114. // files.write(tt.webApiPath, res)
  115. // try {
  116. const data = res
  117. this.scheama({ name, basePath, data })
  118. this.webapi({ name, basePath, data })
  119. // } catch (e) {
  120. // return Promise.resolve({ errInfo: e })
  121. // }
  122. })
  123. .catch((e) => {
  124. cl.logw(`${name}-${basePath}:${e}`)
  125. return Promise.resolve({ errInfo: e })
  126. })
  127. },
  128. /** 生成 scheama文件 .d.ts */
  129. scheama({ name, basePath, data }) {
  130. const curps = files.getIFPath(basePath)
  131. const tss = Object.values(data.definitions)
  132. // 忽略嵌套类型
  133. .filter((f) => !f.title.includes('«'))
  134. .map((m) => {
  135. let descriptions = ''
  136. if (m.properties) {
  137. descriptions = '\n'
  138. for (const [k, v] of Object.entries(m.properties)) {
  139. let curType = ''
  140. if (v.$ref) {
  141. curType = convert.definitions(v.$ref)
  142. } else if (v.type === 'array' && v.items.$ref) {
  143. curType = convert.definitions(v.items.$ref) + '[]'
  144. } else {
  145. curType = convert.dataTypesMap(v.type)
  146. }
  147. descriptions += ` /** ${v.description} */\n ${k}?: ${curType}\n`
  148. }
  149. }
  150. return `interface ${convert.getSafeStr(m.title)} {${descriptions}}`
  151. })
  152. files.write(curps.schemaPath, `/** ${name} */\n${tss.join('\n')}\n`)
  153. },
  154. /** 生成接口配置信息 */
  155. webapi({ name, basePath, data }) {
  156. const curps = files.getIFPath(basePath)
  157. const paths = data.paths
  158. let urlsStr = ''
  159. const urlNameMap = {}
  160. const getUrlName = (url) => {
  161. url = url.replace(/.+\//, '')
  162. if (urlNameMap.hasOwnProperty(url)) {
  163. urlNameMap[url]++
  164. } else {
  165. urlNameMap[url] = 0
  166. }
  167. return url + (urlNameMap[url] ? '_' + urlNameMap[url] : '')
  168. }
  169. for (const [k, v] of Object.entries(paths)) {
  170. const curPostInfo = v.post
  171. if (!curPostInfo) continue
  172. // const urlName = curPostInfo.operationId.replace('UsingPOST', '')
  173. if (k.includes('{')) continue
  174. const urlName = getUrlName(k)
  175. let isUploadStr = ''
  176. let reqTypeStr = ''
  177. let resTypeStr = ''
  178. // 存在入参定义
  179. if (curPostInfo.parameters && curPostInfo.parameters.length) {
  180. /** body类型入参 */
  181. const bodyParameter = curPostInfo.parameters.find((f) => f.in === 'body')
  182. if (bodyParameter) {
  183. const curSchema = bodyParameter.schema
  184. if (curSchema && curSchema.$ref) {
  185. reqTypeStr = ` reqType: {} as ${convert.definitions(curSchema.$ref)},`
  186. }
  187. }
  188. /** query类型入参 */
  189. const queryParameters = curPostInfo.parameters.filter((f) => f.in === 'query')
  190. if (queryParameters.length) {
  191. const curReqType = queryParameters
  192. .map(
  193. (m) =>
  194. `\n /** ${m.description} */\n ${m.name}${m.required ? '' : '?'}: ${convert.dataTypesMap(m.type)}`,
  195. )
  196. .join('')
  197. reqTypeStr = ` reqType: {} as {${curReqType}\n },`
  198. }
  199. /** formData类型入参-- 上传文件 */
  200. const formDataParameters = curPostInfo.parameters.find((f) => f.in === 'formData')
  201. if (formDataParameters) {
  202. isUploadStr = '\n isUpload: true,'
  203. // reqTypeStr = ` reqType: {} as {${`\n /** ${formDataParameters.description} */\n ${formDataParameters.name}${formDataParameters.required ? '' : '?'}: File`}\n },`
  204. }
  205. }
  206. if (
  207. curPostInfo.responses &&
  208. curPostInfo.responses[200] &&
  209. curPostInfo.responses[200].schema &&
  210. curPostInfo.responses[200].schema.$ref
  211. ) {
  212. /** 出参 类型 */
  213. const resTypeSchema = convert.definitions(curPostInfo.responses[200].schema.$ref)
  214. resTypeStr = ` resType: {} as ${resTypeSchema},`
  215. }
  216. urlsStr += `\n /** ${curPostInfo.summary || curPostInfo.summary} */\n ${urlName}: {\n realUrl: '${k}' as const,${isUploadStr}\n${reqTypeStr}\n${resTypeStr}\n },`
  217. }
  218. files.write(
  219. curps.webApiPath,
  220. `export default {${urlsStr}\n}\n`,
  221. // `const ${basePath} = {${urlsStr}\n}\nexport default ${basePath}\n`,
  222. )
  223. },
  224. }
  225. const main = () => {
  226. request.get('/json/group.json').then((res) => {
  227. // res= [{
  228. // "name": "账户中心",
  229. // "url": "/account/v2/api-docs",
  230. // "swaggerVersion": "2.0",
  231. // "location": "/account/v2/api-docs",
  232. // "basePath": "/account"
  233. // }]
  234. // 获取所有控制台参数
  235. const args = process.argv.slice(2) // 去掉第一个和第二个参数(node路径和脚本路径)
  236. // 分组名称-模糊
  237. const gn = args[0]
  238. const groups = gn ? res.filter((f) => f.basePath.includes(gn)) : res
  239. let importStr = ''
  240. let exportStr = ''
  241. Promise.all(
  242. groups.map((f) => {
  243. f.basePath = f.basePath.replace('/', '')
  244. return convert.main(f).then((res) => {
  245. if (res && res.errInfo) {
  246. cl.loge(`${f.name}-${f.basePath}:导入失败×`)
  247. return
  248. } else {
  249. cl.logs(`${f.name}-${f.basePath}:导入成功√`)
  250. }
  251. importStr += `import ${f.basePath} from './${f.basePath}'\n`
  252. exportStr += ` /** ${f.name} */\n ${f.basePath},\n`
  253. })
  254. }),
  255. ).then(() => {
  256. // 根据名称模糊搜索 不写入index.ts
  257. if (gn) return
  258. // 写入 src\utils\config\interFaces\index.ts
  259. const exportFileStr = `${importStr}\nexport default {\n${exportStr}}\n`
  260. const exportsPath = files.getIFPath('index')
  261. files.write(exportsPath.webApiPath, exportFileStr)
  262. })
  263. })
  264. }
  265. main()
  266. const test = () => {
  267. // 获取所有控制台参数
  268. const args = process.argv.slice(2) // 去掉第一个和第二个参数(node路径和脚本路径)
  269. }
  270. // test()