configCenter.js 4.68 KB
/**
 * 配置中心 Schema 拉取与 indexed map → list 转换
 * @see packageDynamicForm/docs/ARCHITECTURE.md
 *
 * fetchConfigCenterTemplate(moduleUrl):GET 配置中心
 * normalizeConfigToSchemaRoot:{ "0": field, ... } → { list: [...] }
 * DYNAMIC_FORM_TEMPLATE_MODULE:三页 moduleUrl 常量
 */
const CONFIG_CENTER_BASE = 'https://config-center-backend.glsx.com.cn/glsxAdmin/config'
const ENV_MAP = ['develop', 'develop', 'test', 'production', 'beta']

/** 解析当前 envIndex,非小程序环境默认 test(2) */
function resolveEnvIndex() {
	if (typeof wx === 'undefined') {
		return 2
	}
	try {
		const { envIndex } = require('~/config.js')
		return envIndex ?? 2
	} catch {
		return 2
	}
}

const DYNAMIC_FORM_TEMPLATE_MODULE = {
	staff: 'staff-daily-template',
	store: 'store-daily-template',
	negotiation: 'negotiation-details-template'
}

const templateCache = new Map()

let requestImpl = null

/** 获取 wx.request 或测试注入的实现 */
function getRequestImpl() {
	if (requestImpl) {
		return requestImpl
	}
	if (typeof wx !== 'undefined' && wx.request) {
		return options =>
			new Promise((resolve, reject) => {
				wx.request({
					...options,
					success: resolve,
					fail: reject
				})
			})
	}
	return null
}

/** 测试注入:覆盖配置中心 HTTP 请求实现 */
function __setConfigCenterRequest(impl) {
	requestImpl = impl
}

/** 生成配置中心模板缓存键 env:moduleUrl */
function getTemplateCacheKey(moduleUrl) {
	const env = ENV_MAP[resolveEnvIndex()] || 'develop'
	return `${env}:${moduleUrl}`
}

/** 判断 payload 是否为数字键字段表 { "0": { key, ... }, ... } */
function isIndexedFieldMap(payload) {
	if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
		return false
	}
	const numericKeys = Object.keys(payload).filter(key => /^\d+$/.test(key))
	if (!numericKeys.length) {
		return false
	}
	return numericKeys.every(key => {
		const item = payload[key]
		return item && typeof item === 'object' && typeof item.key === 'string'
	})
}

/** 数字键字段表 → { version, list } schema root */
function indexedFieldMapToSchemaRoot(payload) {
	const list = Object.keys(payload)
		.filter(key => /^\d+$/.test(key))
		.sort((a, b) => Number(a) - Number(b))
		.map(key => payload[key])
	return { version: '2.0.0', list }
}

/**
 * 将配置中心原始数据规范化为 schema root(支持嵌套 data 与 JSON 字符串)
 * @param {Object|string} raw 配置中心返回的原始 payload
 * @returns {{version: string, list: Array}} schema root
 * @throws {Error} 空数据或格式无效时
 */
function normalizeConfigToSchemaRoot(raw) {
	if (raw == null || raw === '') {
		throw new Error('配置中心返回空数据')
	}
	let payload = raw
	if (typeof raw === 'string') {
		payload = JSON.parse(raw)
	}
	if (payload.data != null && !isIndexedFieldMap(payload)) {
		if (payload.data === '') {
			const hint = payload.message ? `:${payload.message}` : ''
			throw new Error(`配置中心未返回模版数据${hint}`)
		}
		return normalizeConfigToSchemaRoot(payload.data)
	}
	if (!isIndexedFieldMap(payload)) {
		throw new Error('配置中心模版格式无效,需为数字键字段表')
	}
	return indexedFieldMapToSchemaRoot(payload)
}

/**
 * 从配置中心 GET 表单模板(按 env + moduleUrl 缓存)
 * @param {string} moduleUrl 模板 moduleUrl,见 DYNAMIC_FORM_TEMPLATE_MODULE
 * @param {Object} [options={}]
 * @param {boolean} [options.useCache=true] 是否使用进程内缓存
 * @returns {Promise<{code: number, message: string, data: *}>}
 */
function fetchConfigCenterTemplate(moduleUrl, options = {}) {
	const { useCache = true } = options
	if (!moduleUrl) {
		return Promise.reject(new Error('moduleUrl 不能为空'))
	}

	const cacheKey = getTemplateCacheKey(moduleUrl)
	if (useCache && templateCache.has(cacheKey)) {
		return Promise.resolve(templateCache.get(cacheKey))
	}

	const request = getRequestImpl()
	if (!request) {
		return Promise.reject(new Error('wx.request 不可用'))
	}

	const env = ENV_MAP[resolveEnvIndex()] || 'develop'
	const url = `${CONFIG_CENTER_BASE}?moduleUrl=${encodeURIComponent(moduleUrl)}&env=${encodeURIComponent(env)}`

	return request({
		url,
		method: 'GET',
		dataType: 'json',
		responseType: 'text'
	}).then(response => {
		const result = {
			code: 0,
			message: 'ok',
			data: response.data
		}
		if (useCache) {
			templateCache.set(cacheKey, result)
		}
		return result
	})
}

/**
 * 清空配置中心模板进程内缓存
 * @returns {void}
 */
function clearConfigCenterTemplateCache() {
	templateCache.clear()
}

module.exports = {
	CONFIG_CENTER_BASE,
	ENV_MAP,
	DYNAMIC_FORM_TEMPLATE_MODULE,
	normalizeConfigToSchemaRoot,
	fetchConfigCenterTemplate,
	clearConfigCenterTemplateCache,
	__setConfigCenterRequest
}