buildIndex.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * Build an index of models in models/models.ts
  3. *
  4. * The index is of the form :
  5. *
  6. * {
  7. * [entityName]: async () => [entityClass],
  8. * ...
  9. * }
  10. */
  11. import { writeFileSync } from 'fs'
  12. import { glob } from 'glob'
  13. import fs from 'fs'
  14. console.log('Build entity index')
  15. const modules: Array<{ entity: string, path: string }> = []
  16. const files = await glob('./models/*/*.ts')
  17. files.forEach(async (file) => {
  18. const data = fs.readFileSync(file, 'utf8')
  19. const lines = data.split('\n')
  20. let entity = null
  21. for (let line of lines) {
  22. let match = line.match(/static entity = ['"]([\w-/]+)['"]/)
  23. if (match){
  24. // afficher le groupe capturant
  25. entity = match[1]
  26. break
  27. }
  28. }
  29. if (entity) {
  30. modules.push({ entity, path: file })
  31. } else {
  32. console.warn("No match found for entity name in " + file)
  33. }
  34. })
  35. const code = []
  36. code.push('/**')
  37. code.push(' * /!\\ Auto-generated file : do not modify directly /!\\')
  38. code.push(' *')
  39. code.push(' * > This file is generated by the script prepare/buildIndex.ts when running `nuxt prepare`')
  40. code.push('*/')
  41. code.push("import type ApiResource from '~/models/ApiResource'")
  42. code.push('')
  43. // noinspection JSAnnotator
  44. code.push('const modelsIndex: Record<string, () => Promise<typeof ApiResource>> = {')
  45. for (const module of modules) {
  46. code.push(" '" + module.entity + "': async () => {")
  47. code.push(" const module = await import('~/" + module.path.slice(0, -3) + "')")
  48. code.push(' return module.default')
  49. code.push(' },')
  50. }
  51. code.push('}')
  52. code.push('')
  53. code.push('export default modelsIndex')
  54. writeFileSync('models/models.ts', code.join('\n'))