configCenter.js
4.68 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/**
* 配置中心 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
}