@mpxjs/api-proxy 2.8.23-alpha → 2.8.25-alpha.19

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": "@mpxjs/api-proxy",
3
- "version": "2.8.23-alpha",
3
+ "version": "2.8.25-alpha.19",
4
4
  "description": "convert miniprogram API at each end",
5
5
  "module": "src/index.js",
6
6
  "types": "@types/index.d.ts",
@@ -39,5 +39,5 @@
39
39
  "dependencies": {
40
40
  "axios": "^0.21.1"
41
41
  },
42
- "gitHead": "3a6dff432fd46bab36a9866f92cffb6501e69909"
42
+ "gitHead": "fed88f10a76c55cc2be19369b4b754191984d3a3"
43
43
  }
@@ -1,57 +1,48 @@
1
+ const notifyCenter = Hummer.notifyCenter
2
+ const { Memory } = __GLOBAL__
3
+ // 通过Memory 和 notifyCenter实现跨页面事件通道
4
+ // FIXME:可能存在的问题once订阅的移除 emit事件传参数量
1
5
  class EventChannel {
2
- constructor () {
3
- this.listener = {}
4
- }
5
-
6
6
  emit (eventName, ...args) {
7
- const cbs = this.listener[eventName]
8
- if (cbs) {
9
- cbs.forEach((item, index) => {
10
- try {
11
- item.fn.apply(this, args)
12
- } catch (e) {
13
- console.log(`event "${eventName}" error ${e}`)
14
- }
15
- if (item.type === 'once') {
16
- cbs.splice(index, 1)
17
- }
18
- })
7
+ notifyCenter.triggerEvent(eventName, args)
8
+ if (Memory.exist(`_ENENT_ONCE_${eventName}`)) {
9
+ // 订阅和发送可能不是一个上下文 暂时只能全部移除
10
+ this.off(eventName)
11
+ Memory.remove(`_ENENT_ONCE_${eventName}`)
19
12
  }
20
13
  }
21
14
 
22
15
  off (eventName, EventCallback) {
23
- if (EventCallback) {
24
- const cbs = this.listener[eventName]
25
- const copyCbs = []
26
- if (cbs) {
27
- cbs.forEach((item, index) => {
28
- if (item.fn !== EventCallback) {
29
- copyCbs.push(item)
30
- }
31
- })
32
- }
33
- this.listener[eventName] = copyCbs
34
- } else {
35
- this.listener[eventName] && (this.listener[eventName].length = 0)
36
- }
16
+ notifyCenter.removeEventListener(eventName, EventCallback)
37
17
  }
38
18
 
39
19
  on (eventName, EventCallback) {
40
- (this.listener[eventName] || (this.listener[eventName] = [])).push({ fn: EventCallback, type: 'on' })
20
+ notifyCenter.addEventListener(eventName, EventCallback)
41
21
  }
42
22
 
43
23
  once (eventName, EventCallback) {
44
- (this.listener[eventName] || (this.listener[eventName] = [])).push({ fn: EventCallback, type: 'once' })
24
+ notifyCenter.addEventListener(eventName, EventCallback)
25
+ Memory.set(`_ENENT_ONCE_${eventName}`, 1)
45
26
  }
46
27
 
47
28
  _addListener (eventName, EventCallback, type) {
48
- (this.listener[eventName] || (this.listener[eventName] = [])).push({ fn: EventCallback, type })
29
+ switch (type) {
30
+ case 'on':
31
+ this.on(eventName, EventCallback)
32
+ break
33
+ case 'once':
34
+ this.once(eventName, EventCallback)
35
+ break
36
+ default:
37
+ this.on(eventName, EventCallback)
38
+ break
39
+ }
49
40
  }
50
41
 
51
42
  _addListeners (events) {
52
43
  if (Object.prototype.toString.call(events) === '[object Object]') {
53
44
  Object.keys(events).forEach((eventName) => {
54
- (this.listener[eventName] || (this.listener[eventName] = [])).push({ fn: events[eventName], type: 'on' })
45
+ this.on(eventName, events[eventName])
55
46
  })
56
47
  }
57
48
  }
@@ -1,70 +1,84 @@
1
1
  import { webHandleSuccess, webHandleFail } from '../../../common/js'
2
+ import { buildQueryStringUrl, parseHeader, tryJsonParse } from './utils'
2
3
  const { Request } = __GLOBAL__
4
+ const requestFn = new Request()
3
5
 
4
- function request (options = { url: '' }) {
6
+ function request (options = {}) {
5
7
  let {
6
8
  data = {},
7
9
  method = 'GET',
8
- dataType = 'json',
9
- responseType = 'text',
10
+ dataType = 'form',
11
+ responseType = 'json',
10
12
  timeout = 60 * 1000,
11
13
  header = {},
12
14
  success = null,
13
15
  fail = null,
14
- complete = null
16
+ complete = null,
17
+ url = ''
15
18
  } = options
16
19
 
17
20
  method = method.toUpperCase()
18
21
 
19
- if (
20
- method === 'POST' &&
21
- typeof data !== 'string' && // string 不做处理
22
- (header['Content-Type'] === 'application/x-www-form-urlencoded' ||
23
- header['content-type'] === 'application/x-www-form-urlencoded')
24
- ) {
25
- // 重新设置data
26
- data = Object.keys(data)
27
- .reduce((pre, curKey) => {
28
- return `${pre}&${encodeURIComponent(curKey)}=${encodeURIComponent(
29
- data[curKey]
30
- )}`
31
- }, '')
32
- .slice(1)
22
+ if (['GET', 'PUT', 'DELETE'].indexOf(method) > -1) {
23
+ url = buildQueryStringUrl(data, url)
24
+
25
+ if (method === 'GET') {
26
+ data = {}
27
+ }
33
28
  }
34
29
 
35
- const requestFn = new Request()
30
+ switch (dataType) {
31
+ case 'form':
32
+ header = {
33
+ 'Content-Type': 'application/x-www-form-urlencoded',
34
+ ...header
35
+ }
36
+ break
37
+
38
+ case 'json':
39
+ header = {
40
+ 'Content-Type': 'application/json',
41
+ ...header
42
+ }
43
+ break
44
+ }
36
45
 
37
- requestFn.url = options.url
46
+ requestFn.url = url
38
47
  requestFn.method = method
39
48
  requestFn.timeout = timeout
49
+ requestFn.param = data
40
50
  requestFn.header = header
41
- requestFn.params = data
42
- requestFn.send((response) => {
43
- let { status, header: resHeader, data: resData, error } = response
44
- // 返回的数据处理
45
-
46
- if (responseType === 'text' && dataType === 'json') {
47
- try {
48
- resData = JSON.parse(resData)
49
- } catch (e) {}
50
- }
51
51
 
52
- if (status >= 200 && status < 300) {
53
- const result = {
54
- errMsg: 'request:ok',
55
- data: resData,
56
- statusCode: status,
57
- header: resHeader
52
+ return new Promise((resolve, reject) => {
53
+ requestFn.send((response) => {
54
+ let { status, header: resHeader, data: resData, error } = response
55
+ // 返回的数据处理
56
+ if (status >= 200 && status < 300) {
57
+ if (responseType === 'json' && typeof resData === 'string') {
58
+ try {
59
+ resData = JSON.parse(resData)
60
+ } catch (e) {
61
+ console.log('resDataType默认为"json", 尝试对返回内容进行JSON.parse, 但似乎出了些问题(若不希望对结果进行parse, 可传入resDataType: "text"): ', e)
62
+ }
63
+ }
64
+ const result = {
65
+ errMsg: 'request:ok',
66
+ data: resData,
67
+ statusCode: status,
68
+ header: resHeader
69
+ }
70
+ webHandleSuccess(result, success, complete)
71
+ resolve(result)
72
+ } else {
73
+ if (responseType === 'json') {
74
+ resData = tryJsonParse(resData)
75
+ }
76
+ header = parseHeader(header)
77
+ const res = { errMsg: `request:fail ${error.msg}`, data: resData, header }
78
+ webHandleFail(res, fail, complete)
79
+ reject(res)
58
80
  }
59
- webHandleSuccess(result, success, complete)
60
- return result
61
- } else {
62
- const res = { errMsg: `request:fail ${error.msg}` }
63
- webHandleFail(res, fail, complete)
64
- if (!fail) {
65
- return Promise.reject(res)
66
- }
67
- }
81
+ })
68
82
  })
69
83
  }
70
84
 
@@ -0,0 +1,80 @@
1
+ function typeEqual (obj, type) {
2
+ return Object.prototype.toString.call(obj) === '[object ' + type + ']'
3
+ }
4
+
5
+ function isStr (obj) {
6
+ return typeEqual(obj, 'String')
7
+ }
8
+
9
+ export function queryParse (search = '') {
10
+ const arr = search.split(/(\?|&)/)
11
+ const parmsObj = {}
12
+
13
+ for (let i = 0; i < arr.length; i++) {
14
+ if (arr[i].indexOf('=') !== -1) {
15
+ const keyValue = arr[i].match(/([^=]*)=(.*)/)
16
+ parmsObj[keyValue[1]] = decodeURIComponent(keyValue[2])
17
+ }
18
+ }
19
+
20
+ if (JSON.stringify(parmsObj) === '{}') {
21
+ // 如果解析失败,返回原值
22
+ return search
23
+ }
24
+
25
+ return parmsObj
26
+ }
27
+
28
+ export function tryJsonParse (some) {
29
+ // 这里eslint提示也先别删除\[\]
30
+ // eslint-disable-next-line no-useless-escape
31
+ if (isStr(some) && /[\{\[].*[\}\]]/.test(some)) {
32
+ try {
33
+ some = JSON.parse(some)
34
+ } catch (err) {}
35
+ }
36
+
37
+ return some
38
+ }
39
+
40
+ export function parseHeader (headers) {
41
+ // fetch中的headers value为数组形式,其他端为字符串形式, 统一为字符串
42
+ // header的key值统一为小写
43
+ const result = {}
44
+ Object.keys(headers).forEach(key => {
45
+ let value = headers[key]
46
+
47
+ if (value instanceof Array) {
48
+ value = value[0]
49
+ }
50
+
51
+ result[key.toLowerCase()] = value
52
+ })
53
+ return JSON.stringify(result)
54
+ }
55
+
56
+ export function queryStringify (obj) {
57
+ const strArr = []
58
+ let keys = null
59
+
60
+ if (obj && Object.keys(obj).length > 0) {
61
+ keys = Object.keys(obj)
62
+
63
+ for (let i = 0; i < keys.length; i++) {
64
+ const key = keys[i]
65
+ strArr.push(`${key}=${encodeURIComponent(obj[key])}`)
66
+ }
67
+ }
68
+
69
+ return strArr.join('&')
70
+ }
71
+ export function buildQueryStringUrl (params, url = '') {
72
+ if (!url) return queryStringify(params)
73
+ let retUrl = url
74
+
75
+ if (queryStringify(params)) {
76
+ retUrl = url.indexOf('?') > -1 ? `${url}&${queryStringify(params)}` : `${url}?${queryStringify(params)}`
77
+ }
78
+
79
+ return retUrl
80
+ }
@@ -2,14 +2,39 @@ import { webHandleSuccess } from '../../../common/js'
2
2
  import { EventChannel } from '../event-channel'
3
3
  const { Navigator } = __GLOBAL__
4
4
 
5
+ function handleUrl (url) {
6
+ const [urlString, queryString] = url.split('?')
7
+ const queryObj = {}
8
+
9
+ if (!queryString) {
10
+ return {
11
+ query: queryObj,
12
+ url: urlString
13
+ }
14
+ }
15
+
16
+ const paramsArray = queryString.split('&')
17
+ for (const pair of paramsArray) {
18
+ const [key, value] = pair.split('=')
19
+ queryObj[key] = decodeURIComponent(value)
20
+ }
21
+
22
+ return {
23
+ query: queryObj,
24
+ url: urlString
25
+ }
26
+ }
27
+
5
28
  function redirectTo (options = {}) {
29
+ const { url, query } = handleUrl(options.url || '')
6
30
  if (Navigator) {
7
- Navigator.__mpxAction = { type: 'redirect' }
8
31
  return new Promise((resolve, reject) => {
9
32
  // 关闭本页面的跳转
10
33
  Navigator.openPage(
11
34
  {
12
- url: options.url,
35
+ url,
36
+ animated: false,
37
+ params: query,
13
38
  closeSelf: true
14
39
  },
15
40
  // 执行环境变了 得不到执行的机会 故回调无效
@@ -23,25 +48,22 @@ function redirectTo (options = {}) {
23
48
  }
24
49
 
25
50
  function navigateTo (options = {}) {
51
+ const { url, query } = handleUrl(options.url || '')
52
+ const events = options.events
53
+
26
54
  if (Navigator) {
27
55
  const eventChannel = new EventChannel()
28
- Navigator.__mpxAction = {
29
- type: 'to',
30
- eventChannel
31
- }
32
- if (options.events) {
33
- eventChannel._addListeners(options.events)
56
+ if (events) {
57
+ eventChannel._addListeners(events)
34
58
  }
35
59
  return new Promise((resolve, reject) => {
36
60
  // 不关闭本页面的跳转
37
- Navigator.openPage(
38
- {
39
- url: options.url
40
- },
41
- // 执行环境变了 得不到执行的机会 故回调无效
42
- () => {}
43
- )
44
- const res = { errMsg: 'redirectTo:ok' }
61
+ Navigator.openPage({
62
+ url,
63
+ animated: true,
64
+ params: query
65
+ }, () => {})
66
+ const res = { errMsg: 'redirectTo:ok', eventChannel }
45
67
  webHandleSuccess(res, options.success, options.complete)
46
68
  resolve(res)
47
69
  })
@@ -51,12 +73,9 @@ function navigateTo (options = {}) {
51
73
  function navigateBack (options = {}) {
52
74
  if (Navigator) {
53
75
  const delta = options.delta || 1
54
- Navigator.__mpxAction = {
55
- type: 'back',
56
- delta
57
- }
58
- // popBack方法
59
- Navigator.popBack(delta, { animated: true })
76
+ Navigator.popBack(delta, {
77
+ animated: true
78
+ })
60
79
  const res = { errMsg: 'navigateBack:ok' }
61
80
  webHandleSuccess(res, options.success, options.complete)
62
81
  return Promise.resolve(res)
@@ -0,0 +1,17 @@
1
+ import { webHandleSuccess } from '../../../common/js'
2
+ const {
3
+ Hummer
4
+ } = __GLOBAL__
5
+
6
+ function setNavigationBarTitle (options = {}) {
7
+ const { title, success, complete } = options
8
+ Hummer.setTitle(title)
9
+ webHandleSuccess({ errMsg: 'setTitle:ok' }, success, complete)
10
+ }
11
+
12
+ function setNavigationBarColor (options = {}) {}
13
+
14
+ export {
15
+ setNavigationBarTitle,
16
+ setNavigationBarColor
17
+ }