buildIndex.ts 1.6 KB

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