22
schangxiang@126.com
2025-04-29 3fdd40af6a7c4ca1b9c833fd7fbe17a9bcc9258f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { onBeforeMount, onUnmounted, reactive, ref, toRefs, Ref } from 'vue'
import set from 'lodash/set'
import get from 'lodash/get'
 
interface ControllerType {
  Models: Record<string, Function>
}
 
let Modules = {}
/**
 * 获取文件名
 * @param filePath
 * @returns
 */
const extractNameFromPath = (filePath: string) => {
  const regex = /\/([^\/0-9][A-Za-z-0-9]+)\.ts$/
  const match = filePath.match(regex)
 
  if (match && match[1]) {
    return match[1]
  } else {
    return null
  }
}
 
/**
 * 转换成名称函数数组
 * @param fileMap
 */
const getFunctionByName = (fileMap: Record<string, Function>) => {
  const entries = Object.entries(fileMap)
  return entries.map(([filePath, fn]) => {
    const name = extractNameFromPath(filePath)
    if (name) {
      return [name, fn]
    } else {
      throw new Error(`${filePath} 文件名格式不正确,请检查`)
    }
  })
}
 
/**
 * 存入modules
 * @param data [[a,b]]
 * @param namespace
 * @param bool 是否实例化类,默认为false
 */
const saveModules = (data: (string | Function)[][]) => {
  for (let i = 0; i < data.length; i++) {
    const [name, Module]: any[] = data[i]
 
    Object.entries(Module).map(([hookName, fn]: any) => {
      const fnKey = hookName.toLocaleLowerCase()
      try {
        set(Modules, fnKey, new fn())
      } catch (error) {
        console.error(error)
        throw new Error(`${name} 类中 ${fnKey} 方法格式不正确,请检查`)
      }
    })
  }
}
 
/**
 * 初始化models
 * @param param
 */
export const createModels = ({ Models }: ControllerType) => {
  const models = getFunctionByName(Models)
  saveModules(models)
}
 
/**
 * 获取model
 * @param modelName
 * @returns
 */
export const injectModel = <T>(modelName: string): T => {
  const key = modelName.toLocaleLowerCase()
  const InstanceModel = get(Modules, key)
  return InstanceModel
}
 
/**
 * 获取全局models
 * @param modelName
 * @returns
 */
export const injectModels = () => {
  return Modules
}