222
schangxiang@126.com
2025-05-06 38b161e4d52362081bfe78fb5b51fbf384db7ce2
HIAWms/web/src/libs/Provider/Provider.ts
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,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
}