generate-api.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* eslint-env node */
  2. import http from 'http'
  3. import fs from 'fs'
  4. import fse from 'fs-extra'
  5. import { v4 as uuidv4 } from 'uuid'
  6. import os from 'os'
  7. import path from 'path'
  8. import AdmZip from 'adm-zip'
  9. const sourceUrl = 'http://58.87.69.234:9902/ts.zip'
  10. //const sourceUrl = 'http://localhost:9902/ts.zip'
  11. const tmpFilePath = os.tmpdir() + '/' + uuidv4() + '.zip'
  12. const generatePath = 'src/apis/__generated'
  13. console.log('Downloading ' + sourceUrl + '...')
  14. const tmpFile = fs.createWriteStream(tmpFilePath)
  15. http.get(sourceUrl, (response) => {
  16. response.pipe(tmpFile)
  17. tmpFile.on('finish', () => {
  18. tmpFile.close()
  19. console.log('File save success: ', tmpFilePath)
  20. // Remove generatePath if it exists
  21. if (fs.existsSync(generatePath)) {
  22. console.log('Removing existing generatePath...')
  23. fse.removeSync(generatePath)
  24. console.log('Existing generatePath removed.')
  25. }
  26. // Unzip the file using adm-zip
  27. console.log('Unzipping the file...')
  28. const zip = new AdmZip(tmpFilePath)
  29. zip.extractAllTo(generatePath, true)
  30. console.log('File unzipped successfully.')
  31. // Remove the temporary file
  32. console.log('Removing temporary file...')
  33. fs.unlink(tmpFilePath, (err) => {
  34. if (err) {
  35. console.error('Error while removing temporary file:', err)
  36. } else {
  37. console.log('Temporary file removed.')
  38. }
  39. })
  40. traverseDirectory(modelPath)
  41. traverseDirectory(servicePath)
  42. })
  43. })
  44. // 替换目录路径
  45. const modelPath = 'src/apis/__generated/model'
  46. const servicePath = 'src/apis/__generated/services'
  47. // 递归遍历目录中的所有文件
  48. function traverseDirectory(directoryPath) {
  49. const files = fs.readdirSync(directoryPath)
  50. files.forEach((file) => {
  51. const filePath = path.join(directoryPath, file)
  52. const stats = fs.statSync(filePath)
  53. if (stats.isDirectory()) {
  54. traverseDirectory(filePath)
  55. } else if (stats.isFile() && path.extname(filePath) === '.ts') {
  56. replaceInFile(filePath)
  57. }
  58. })
  59. }
  60. // 替换文件中的文本
  61. function replaceInFile(filePath) {
  62. const fileContent = fs.readFileSync(filePath, 'utf8')
  63. const updatedContent = fileContent
  64. .replaceAll('readonly ', '')
  65. .replace(/ReadonlyArray/g, 'Array')
  66. .replaceAll('ReadonlyMap', 'Map')
  67. .replace(/Map<(\S+), (\S+)>/g, '{ [key: $1]: $2 }')
  68. // .replace(/query: (\S+)/g, 'query: T')
  69. fs.writeFileSync(filePath, updatedContent, 'utf8')
  70. }