@tmsfe/tms-core 0.0.95 → 0.0.96

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tmsfe/tms-core",
3
- "version": "0.0.95",
3
+ "version": "0.0.96",
4
4
  "description": "tms运行时框架",
5
5
  "repository": {
6
6
  "type": "git",
package/src/config.js CHANGED
@@ -87,6 +87,46 @@ function getConfig(configPath, extendAttr = {}, defaultCfg) {
87
87
  });
88
88
  }
89
89
 
90
+ /**
91
+ * getApolloConfig 获取阿波罗平台配置
92
+ * @description 拉取阿波罗的配置内容。参见{@link http://mapollo.woa.com/#/26fdbf3}
93
+ * @example <caption>拉取单个配置</caption>
94
+ * const { tms } = getApp({ allowDefault: true });
95
+ * const cfg = await tms.getApolloConfig('sinan_me_faq', {}, { name: '默认配置'})
96
+ * console.log(cfg); // 成功则返回服务端存储的配置,失败返回默认值
97
+ * @param {String|Array} configPath 配置路径,单个路径或配置路径数组,支持替换${client}为当前小程序。例如在出行小程序,${client}会变替换为sinan
98
+ * @param {Object} extendAttr 扩展属性,用于自定义的过滤条件,保留字段 businessKey、moduleKey。
99
+ * @param {Object} [defaultCfg] 默认配置,请求失败返回默认值。
100
+ * @returns {Promise<Object|Array<Object>>}
101
+ * 有默认值时,请求失败返回默认值。无默认值时,请求失败返回Promise.reject
102
+ */
103
+ function getApolloConfig(configPath, extendAttr = {}, defaultCfg) {
104
+ const configPaths = formatConfigPaths(configPath);
105
+ const defaultCfgs = (defaultCfg && (Array.isArray(defaultCfg) ? defaultCfg : [defaultCfg])) || null;
106
+ const { businessKey, moduleKey, ...extendAttrs } = extendAttr;
107
+ const api = new Request();
108
+ return api.post('marketing/apollo/config', {
109
+ businessKey,
110
+ moduleKey,
111
+ configPaths,
112
+ extendAttrs: JSON.stringify(extendAttrs),
113
+ })
114
+ .then((res) => {
115
+ const { errCode, resData = {} } = res || {};
116
+ const { status, msg, data } = resData;
117
+ if (errCode === 0 && status === 0) {
118
+ return data.map(item => item.content);
119
+ }
120
+ throw new Error(msg);
121
+ })
122
+ .catch((e) => {
123
+ if (defaultCfgs) return Promise.resolve(defaultCfgs);
124
+ return Promise.reject({ err: e, msg: `获取${configPaths.join(',')}配置失败` });
125
+ });
126
+ }
127
+
90
128
  export {
91
129
  getConfig,
130
+ getApolloConfig,
92
131
  };
132
+
@@ -68,7 +68,7 @@ const asyncFuncNames = [
68
68
  // 这行是runtime的
69
69
  'getPhone', 'registerPhone', 'login', 'getLoginInfo', 'getOpenId', 'getMycarPubOpenId', 'getSinanPubOpenId',
70
70
  // tms-core
71
- 'setAuthInfo', 'getConfig', 'navigateToWebview', 'callCloudFunc', 'getEncryptUserInfo',
71
+ 'setAuthInfo', 'getConfig', 'getApolloConfig', 'navigateToWebview', 'callCloudFunc', 'getEncryptUserInfo',
72
72
  'setUserLocation', 'getUserLocation', 'getMpOpenId', 'getOuterOpenId',
73
73
  ];
74
74
  asyncFuncNames.forEach((funcName) => {
package/src/index.js CHANGED
@@ -6,7 +6,7 @@ import runtime from './runtime/index';
6
6
  import Request from './request';
7
7
  import AutoReport from './report/proxy/index';
8
8
  import Reporter from './report/index';
9
- import { getConfig } from './config';
9
+ import { getConfig, getApolloConfig } from './config';
10
10
  import syncApi from './syncfnmanager';
11
11
  import nav from './navigator';
12
12
  import { getLogManager, getRealtimeLogManager } from './log';
@@ -179,6 +179,7 @@ const api = {
179
179
  getEventDispatcher,
180
180
  getEnvInfo,
181
181
  getConfig,
182
+ getApolloConfig,
182
183
  navigateToWebview: nav.navigateToWebview,
183
184
  isAppPageExist,
184
185
  getHomePage,
@@ -3,6 +3,9 @@ import { getSetting, updateLocStatus, getSystemInfo, getTextByReason, openSettin
3
3
  import EventDispatcher from '../eventDispatcher';
4
4
  import { WxPostionType } from '../types/object'; // eslint-disable-line
5
5
 
6
+ const logger = wx.getLogManager({});
7
+ logger.log('location模块代码被装载');
8
+
6
9
  const event = new EventDispatcher();
7
10
 
8
11
  let getLocPromise: null | Promise<any> = null;
@@ -13,6 +16,19 @@ const defaultLocationType = 'gcj02';
13
16
  // 派发事件的名称
14
17
  const EventName = 'loc_status_changed';
15
18
 
19
+ // 小程序切换到前台|后台之后清除缓存,使后续能重新定位获取到最新位置
20
+ function cleanCache(type: string) {
21
+ if (getLocPromise || userLocationCache) {
22
+ getLocPromise = null;
23
+ userLocationCache = undefined;
24
+ logger.log(type, '清除location缓存');
25
+ } else {
26
+ logger.log(type, 'location无缓存需要清理');
27
+ }
28
+ }
29
+ wx.onAppShow(() => cleanCache('wx.onAppShow'));
30
+ wx.onAppHide(() => cleanCache('wx.onAppHide'));
31
+
16
32
  /**
17
33
  * @private 将wx.getLocation获取位置方法用promise封装
18
34
  * @param { string } type 获取位置类型
@@ -23,9 +39,13 @@ function getWxLocation(type: string = defaultLocationType): Promise<WxPostionTyp
23
39
  wx.getLocation({
24
40
  type,
25
41
  success: (res: WxPostionType) => {
42
+ logger.log(`wx.getLocation('${type}') 成功:\n`, JSON.stringify(res, null, ' '));
26
43
  resolve(res);
27
44
  },
28
- fail: reject,
45
+ fail: (err) => {
46
+ logger.warn(`wx.getLocation('${type}') 失败:\n`, JSON.stringify(err, null, ' '));
47
+ reject(err);
48
+ },
29
49
  });
30
50
  });
31
51
  }
@@ -46,8 +66,8 @@ class LocationBase {
46
66
  listenerLocation() {
47
67
  if (!isListenerLocation) {
48
68
  isListenerLocation = true;
49
- wx.onLocationChange(this.subscribeLocationChnage);
50
- wx.startLocationUpdate({});
69
+ wx.onLocationChange(this.subscribeLocationChange);
70
+ wx.startLocationUpdate({}).then();
51
71
  }
52
72
  }
53
73
 
@@ -184,7 +204,7 @@ class LocationBase {
184
204
  * @param { object } res 用户位置信息对象
185
205
  * @returns { undefined } no retrurn
186
206
  */
187
- public subscribeLocationChnage(res: WxPostionType) {
207
+ public subscribeLocationChange(res: WxPostionType) {
188
208
  userLocationCache = res;
189
209
  }
190
210
 
@@ -4,8 +4,8 @@
4
4
  */
5
5
 
6
6
  const maxArrLen = 10;
7
- const maxStrLen = 200;
8
- const maxFieldLen = 20;
7
+ const maxStrLen = 50;
8
+ const maxFieldLen = 10;
9
9
 
10
10
  // 字符串字段白名单,白名单内的字段不截断
11
11
  const fieldWhiteList = [
@@ -48,9 +48,9 @@ function isArrayType(obj: any): { isArray: boolean, value: any } {
48
48
  * @param depth 当前克隆的深度
49
49
  * @param maxDepth 最大克隆深度
50
50
  */
51
- function deepClone(obj: any, depth = 0, maxDepth = 5): any {
51
+ function deepClone(obj: any, depth = 0, maxDepth = 2): any {
52
52
  if (depth > maxDepth) {
53
- return undefined;
53
+ return '深度超过上限,截断';
54
54
  }
55
55
  const res1 = isBasicsType(obj);
56
56
  if (res1.isBasics) {
@@ -9,6 +9,9 @@ import sender from './sender';
9
9
  import formatV1 from './formatV1';
10
10
  import formatV2 from './formatV2';
11
11
 
12
+ const logger = wx.getLogManager({});
13
+ logger.log('report模块代码被装载');
14
+
12
15
  /**
13
16
  * 初始化
14
17
  * @private
@@ -25,6 +28,7 @@ function init(options: IInitOptions): void {
25
28
  */
26
29
  function report(data: IOldParams = {}): void {
27
30
  if (helper.canReport()) {
31
+ logger.log('旧埋点:', data);
28
32
  formatV1.formatData(data).then(arr => sender.queue(arr));
29
33
  }
30
34
  }
@@ -37,6 +41,7 @@ function report(data: IOldParams = {}): void {
37
41
  */
38
42
  function fastReport(data: IOldParams = {}): void {
39
43
  if (helper.canReport()) {
44
+ logger.log('旧立即埋点:', data);
40
45
  const arr = formatV1.formatFastData(data);
41
46
  sender.send(arr);
42
47
  }
@@ -55,6 +60,7 @@ function fastReport(data: IOldParams = {}): void {
55
60
  */
56
61
  function report2(...data: any[]): void {
57
62
  if (helper.canReport()) {
63
+ logger.log('新埋点:', data);
58
64
  formatV2.formatData(data).then(arr => sender.queue(arr));
59
65
  }
60
66
  }
@@ -73,6 +79,7 @@ function report2(...data: any[]): void {
73
79
  */
74
80
  function fastReport2(...data: any[]): void {
75
81
  if (helper.canReport()) {
82
+ logger.log('新立即埋点:', data);
76
83
  const arr = formatV2.formatFastData(data);
77
84
  sender.send(arr);
78
85
  }
package/src/request.js CHANGED
@@ -9,10 +9,11 @@
9
9
  * 框架判断在不同的运行环境,切换调用不同运行环境提供的方法。
10
10
  */
11
11
  import md5 from './md5';
12
- import { getLogManager } from './log';
13
12
  import { getEnvInfo, getAuthInfo } from './env';
14
13
  import { safeJsonParse } from './objUtils';
15
14
 
15
+ const logger = wx.getLogManager({});
16
+
16
17
  /**
17
18
  * 用于序列化需要签名的参数
18
19
  * @private
@@ -144,11 +145,11 @@ export default class Request {
144
145
  }
145
146
 
146
147
  /**
147
- * 格式化接口路径
148
- * @private
149
- * @param {string} path 需要格式化的接口路径
150
- * @returns {string} 格式化后的接口路径
151
- */
148
+ * 格式化接口路径
149
+ * @private
150
+ * @param {string} path 需要格式化的接口路径
151
+ * @returns {string} 格式化后的接口路径
152
+ */
152
153
  makeUrl(path) {
153
154
  if ((/^http/i).test(path)) return path;
154
155
  const host = this.host || Request.defaultHost;
@@ -288,10 +289,10 @@ export default class Request {
288
289
  async serialize(path, data = {}) {
289
290
  let url = this.makeUrl(path);
290
291
  const signData = await composeParam(data, this.withAuth, this.baseParam);
291
- const signture = sign(signData);
292
+ const signature = sign(signData);
292
293
  const params = [];
293
- Object.keys(signture).forEach((key) => {
294
- const val = encodeURIComponent(signture[key]);
294
+ Object.keys(signature).forEach((key) => {
295
+ const val = encodeURIComponent(signature[key]);
295
296
  params.push(`${key}=${val}`);
296
297
  });
297
298
  if (params.length) url += (/\?/.test(url) ? '&' : '?') + params.join('&');
@@ -310,23 +311,46 @@ export default class Request {
310
311
  async createRequestTask(path, param = {}, method = 'POST', header = {}) {
311
312
  const requestParam = await composeParam(param, this.withAuth, this.baseParam);
312
313
  const data = sign(requestParam);
313
- const logger = getLogManager();
314
- const res = await new Promise((resolve, reject) => {
314
+ return new Promise((resolve, reject) => {
315
315
  wx.request({
316
316
  url: this.makeUrl(path),
317
317
  header,
318
318
  method,
319
319
  data,
320
320
  success: (res) => {
321
+ // 埋点已经单独打日志了,接口请求数据日志太长影响分析
322
+ if (path.indexOf('basic/event/upload') === -1) {
323
+ let result = JSON.stringify(res?.data);
324
+ if (result.length > 500) {
325
+ result = `${result.substring(0, 500)} 内容太长被截断`;
326
+ }
327
+ const obj = {
328
+ path,
329
+ method,
330
+ header: JSON.stringify(header),
331
+ params: JSON.stringify(data),
332
+ res: result,
333
+ };
334
+ const str = JSON.stringify(obj, null, ' ').replace(/\\"/ig, '\'');
335
+ logger.log(`接口请求成功:\n${str}`);
336
+ }
337
+
321
338
  resolve(res);
322
- logger.log({ path, header, method, param: data, res: res?.data });
323
339
  },
324
340
  fail: (err) => {
341
+ const obj = {
342
+ path,
343
+ method,
344
+ header: JSON.stringify(header),
345
+ params: JSON.stringify(data),
346
+ err: JSON.stringify(err),
347
+ };
348
+ const str = JSON.stringify(obj, null, ' ').replace(/\\"/ig, '\'');
349
+ logger.error(`接口请求失败:\n${str}`);
350
+
325
351
  reject(err);
326
- logger.log({ path, header, method, param: data, err });
327
352
  },
328
353
  });
329
354
  });
330
- return res;
331
355
  }
332
356
  }