├── .gitignore
├── .npmignore
├── .travis.yml
├── src
├── wxp.js
└── core.js
├── demo
└── demo1
│ ├── app.wxss
│ ├── app.json
│ ├── pages
│ └── index
│ │ ├── index.wxss
│ │ ├── index.wxml
│ │ └── index.js
│ ├── project.config.json
│ ├── app.js
│ └── lib
│ └── wxp.js
├── .babelrc
├── webpack.config.js
├── package.json
├── LICENSE
├── dist
├── wxp.min.js
└── wxp.js
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | .vscode/
3 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | demo
3 | .vscode
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - "8"
4 | script:
5 | - npm run build
6 |
--------------------------------------------------------------------------------
/src/wxp.js:
--------------------------------------------------------------------------------
1 | import CoreClass from './core';
2 | const wxp = new CoreClass();
3 | wxp.$init(wxp);
4 | wxp.use('promisify');
5 | wxp.use('requestfix');
6 | export default wxp
--------------------------------------------------------------------------------
/demo/demo1/app.wxss:
--------------------------------------------------------------------------------
1 | /**app.wxss**/
2 | .container {
3 | height: 100%;
4 | display: flex;
5 | flex-direction: column;
6 | align-items: center;
7 | justify-content: space-between;
8 | padding: 200rpx 0;
9 | box-sizing: border-box;
10 | }
11 |
--------------------------------------------------------------------------------
/demo/demo1/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "pages":[
3 | "pages/index/index"
4 | ],
5 | "window":{
6 | "backgroundTextStyle":"light",
7 | "navigationBarBackgroundColor": "#fff",
8 | "navigationBarTitleText": "WeChat",
9 | "navigationBarTextStyle":"black"
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | ["env",
4 | {
5 | "targets": {
6 | "browsers": "last 2 versions, > 1%, Android >= 4, iOS >= 6, and_uc > 9",
7 | "node": "8.0"
8 | },
9 | "modules": false
10 | }]
11 | ]
12 | }
--------------------------------------------------------------------------------
/demo/demo1/pages/index/index.wxss:
--------------------------------------------------------------------------------
1 | /**index.wxss**/
2 | .userinfo {
3 | display: flex;
4 | flex-direction: column;
5 | align-items: center;
6 | }
7 |
8 | .userinfo-avatar {
9 | width: 128rpx;
10 | height: 128rpx;
11 | margin: 20rpx;
12 | border-radius: 50%;
13 | }
14 |
15 | .userinfo-nickname {
16 | color: #aaa;
17 | }
18 |
19 | .usermotto {
20 | margin-top: 200px;
21 | }
--------------------------------------------------------------------------------
/demo/demo1/pages/index/index.wxml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | {{userInfo.nickName}}
8 |
9 |
10 |
11 | {{motto}}
12 |
13 |
14 |
--------------------------------------------------------------------------------
/demo/demo1/project.config.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "项目配置文件。",
3 | "setting": {
4 | "urlCheck": true,
5 | "es6": true,
6 | "postcss": false,
7 | "minified": false,
8 | "newFeature": true
9 | },
10 | "compileType": "miniprogram",
11 | "libVersion": "1.9.93",
12 | "appid": "touristappid",
13 | "projectname": "demo1",
14 | "condition": {
15 | "search": {
16 | "current": -1,
17 | "list": []
18 | },
19 | "conversation": {
20 | "current": -1,
21 | "list": []
22 | },
23 | "game": {
24 | "currentL": -1,
25 | "list": []
26 | },
27 | "miniprogram": {
28 | "current": -1,
29 | "list": []
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/webpack.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const webpack = require('webpack');
3 | const UnminifiedWebpackPlugin = require('unminified-webpack-plugin');
4 | module.exports = {
5 | mode: 'production',
6 | entry: './src/wxp.js',
7 | output: {
8 | filename: 'wxp.min.js',
9 | path: __dirname + '/dist/',
10 | libraryTarget: 'umd'
11 | },
12 | module: {
13 | rules: [
14 | {
15 | test: /\.js$/,
16 | loader: 'babel-loader',
17 | exclude: /node_modules/
18 | }
19 | ]
20 | },
21 | optimization: {
22 | minimize: true,
23 | },
24 | plugins: [
25 | new UnminifiedWebpackPlugin({
26 | postfix: ''
27 | })
28 | ]
29 | }
--------------------------------------------------------------------------------
/demo/demo1/app.js:
--------------------------------------------------------------------------------
1 | //app.js
2 | import wxp from './lib/wxp.js'
3 | // var wxp = require('./lib/wxp').default
4 | console.log(wxp)
5 | App({
6 | onLaunch: function () {
7 |
8 |
9 | // 登录
10 | wxp.login().then(resp => {
11 | console.log('调起登陆授权:', resp)
12 | })
13 | // 获取用户信息
14 | wxp.getSetting().then(res => {
15 | if (res.authSetting['scope.userInfo']) {
16 | // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
17 | wxp.getUserInfo().then(res => {
18 | // 可以将 res 发送给后台解码出 unionId
19 | this.globalData.userInfo = res.userInfo
20 | // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
21 | // 所以此处加入 callback 以防止这种情况
22 | if (this.userInfoReadyCallback) {
23 | this.userInfoReadyCallback(res)
24 | }
25 | })
26 | }
27 | }).catch( ({errMsg}) => {
28 | // 没有获取到用户信息
29 | wxp.showToast({
30 | title: errMsg,
31 | icon: 'none'
32 | })
33 | })
34 | },
35 | globalData: {
36 | userInfo: null
37 | }
38 | })
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "minapp-api-promise",
3 | "version": "1.0.2",
4 | "description": "微信小程序所有API promise化,支持await;支持请求列队",
5 | "main": "dist/wxp.min.js",
6 | "scripts": {
7 | "build": "webpack",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "keywords": [
11 | "微信小程序",
12 | "promise",
13 | "minapp"
14 | ],
15 | "author": "bigMeow (https://github.com/bigmeow/)",
16 | "license": "MIT",
17 | "repository": {
18 | "type": "git",
19 | "url": "https://github.com/bigmeow/minapp-api-promise/tree/master"
20 | },
21 | "bugs": {
22 | "url": "https://github.com/bigmeow/minapp-api-promise/issues"
23 | },
24 | "devDependencies": {
25 | "babel-core": "^6.26.0",
26 | "babel-loader": "^7.1.4",
27 | "babel-plugin-transform-runtime": "^6.23.0",
28 | "babel-preset-env": "^1.6.1",
29 | "babel-preset-stage-2": "^6.24.1",
30 | "unminified-webpack-plugin": "^2.0.0",
31 | "webpack": "^4.25.1",
32 | "webpack-cli": "^2.0.13"
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2018 bigmeow
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | this software and associated documentation files (the "Software"), to deal in
7 | the Software without restriction, including without limitation the rights to
8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | the Software, and to permit persons to whom the Software is furnished to do so,
10 | subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 |
--------------------------------------------------------------------------------
/demo/demo1/pages/index/index.js:
--------------------------------------------------------------------------------
1 | import wxp from '../../lib/wxp.js'
2 | //获取应用实例
3 | const app = getApp()
4 |
5 | Page({
6 | data: {
7 | motto: 'Hello World',
8 | userInfo: {},
9 | hasUserInfo: false,
10 | canIUse: wxp.canIUse('button.open-type.getUserInfo')
11 | },
12 | onLoad: function () {
13 | if (app.globalData.userInfo) {
14 | this.setData({
15 | userInfo: app.globalData.userInfo,
16 | hasUserInfo: true
17 | })
18 | } else if (this.data.canIUse){
19 | // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
20 | // 所以此处加入 callback 以防止这种情况
21 | app.userInfoReadyCallback = res => {
22 | this.setData({
23 | userInfo: res.userInfo,
24 | hasUserInfo: true
25 | })
26 | }
27 | } else {
28 | // 在没有 open-type=getUserInfo 版本的兼容处理
29 | wxp.getUserInfo().then(res => {
30 | app.globalData.userInfo = res.userInfo
31 | this.setData({
32 | userInfo: res.userInfo,
33 | hasUserInfo: true
34 | })
35 | })
36 | }
37 | },
38 | getUserInfo: function(e) {
39 | console.log(e)
40 | app.globalData.userInfo = e.detail.userInfo
41 | this.setData({
42 | userInfo: e.detail.userInfo,
43 | hasUserInfo: true
44 | })
45 | }
46 | })
47 |
--------------------------------------------------------------------------------
/dist/wxp.min.js:
--------------------------------------------------------------------------------
1 | !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var r in n)("object"==typeof exports?exports:e)[r]=n[r]}}(window,function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.r=function(e){Object.defineProperty(e,"__esModule",{value:!0})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=0)}([function(e,t,n){"use strict";n.r(t);var r=function(){function e(e,t){for(var n=0;n-1||this.running.indexOf(e.t)>-1;)e.t+=10*Math.random()>>0;this.mq.push(e.t),this.map[e.t]=e},next:function(){var e=this;if(0!==this.mq.length&&this.running.length1&&void 0!==arguments[1]?arguments[1]:{};this.$initAPI(e,t.noPromiseAPI)}},{key:"use",value:function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;rwebpack),可以通过npm下载安装代码***
18 | ```bash
19 | $ npm install minapp-api-promise --save
20 | ```
21 | 引入代码
22 | ```js
23 | import WXP from 'minapp-api-promise'
24 | ```
25 |
26 | ***如果你没有使用任何脚手架,用官方提供的微信开发者工具开发,请拷贝项目dist目录下的wxp.js文件到你的项目目录***
27 | 引入代码
28 | ```js
29 | import WXP from '项目相对路径/wxp'
30 | ```
31 | 或者
32 | ```js
33 | var WXP = require('项目相对路径/wxp').default
34 | ```
35 | 具体你可以参照 [demo1](https://github.com/bigmeow/minapp-api-promise/tree/master/demo/demo1),并且注意没有脚手架这种情况下你不能使用async/await,只能使用then/catch
36 |
37 |
38 |
39 |
40 |
41 | ***小程序原生用法:***
42 | ```js
43 | onLoad () {
44 | wx.request({
45 | url: 'http://baidu.com',
46 | success: resp => {
47 | console.log('success信息:', resp)
48 | },
49 | fail: errorMesg => {
50 | console.log('fail信息:', errorMesg)
51 | },
52 | complete: resp => {
53 | console.log('complete一定会执行:', resp)
54 | }
55 | })
56 | }
57 | ```
58 |
59 | ***使用了本库后的async/await写法:***
60 | ```js
61 | async onLoad () {
62 | try {
63 | let resp = await WXP.request({
64 | url: 'http://baidu.com'
65 | })
66 | console.log('success信息:', resp)
67 | } catch (errorMesg) {
68 | console.log('fail信息:', errorMesg)
69 | } finally () {
70 | console.log('complete一定会执行')
71 | }
72 | }
73 | ```
74 |
75 | ***你也可以使用promise的then/catch写法:***
76 | ```js
77 | onLoad () {
78 | WXP.request({
79 | url: 'http://baidu.com'
80 | }).then(resp => {
81 | console.log('success信息:', resp)
82 | }).catch(errorMesg => {
83 | console.log('fail信息:', errorMesg)
84 | })
85 | }
86 | ```
87 |
88 | 其他所有的微信小程序原生api(具备异步回调函数的api)使用方法同上
89 |
90 | ### 进阶说明
91 |
92 | ### interceptor 拦截器
93 | 可以使用全局拦截器对原生API接口进行拦截
94 | ⚠️注意:这里不仅仅局限于Http请求的拦截!
95 | 比如某些页面需要登录才能看,我们可以拦截路由,在跳转前判断跳转的页面是否需要登录:
96 | ```js
97 | WXP.intercept('navigateTo', {
98 | config (config) {
99 | console.log('路由跳转前需要处理的事情')
100 | if (页面没有权限) {
101 | // 返回false 后,就不会再执行跳转轻轻
102 | return false;
103 | }
104 | return config;
105 | }
106 | })
107 | // 这样调用就会进入拦截
108 | WXP.navigateTo(配置);
109 | ```
110 | 比如某些API请求需要在请求头带上token。
111 | 参考示例(拦截小程序发起的原生请求):
112 | ```js
113 | import WXP from 'minapp-api-promise'
114 |
115 | WXP.intercept('request', {
116 |
117 | // 发出请求时的回调函数
118 | config (playload) {
119 | // 对所有request请求中的OBJECT参数对象统一附加时间戳属性
120 | playload.timestamp = +new Date();
121 | console.log('request before config: ', playload);
122 | // 必须返回OBJECT参数对象,否则无法发送请求到服务端
123 | return playload;
124 | },
125 |
126 | // 请求成功后的回调函数
127 | success (resp) {
128 | // 可以在这里对收到的响应数据对象进行加工处理
129 | console.log('request success: ', resp);
130 | // 必须返回响应数据对象,否则后续无法对响应数据进行处理
131 | return resp
132 | },
133 |
134 | //请求失败后的回调函数
135 | fail (resp) {
136 | console.log('request fail: ', resp);
137 | // 必须返回响应数据对象,否则后续无法对响应数据进行处理
138 | return resp;
139 | },
140 |
141 | // 请求完成时的回调函数(请求成功或失败都会被执行)
142 | complete (resp) {
143 | console.log('request complete: ', resp);
144 | }
145 |
146 | })
147 | ```
148 |
149 |
150 | #### 顺手附上一个实际项目中的使用示例:
151 | requestIntercept.js
152 | ```js
153 | /*
154 | * @description: 网络请求拦截器(注意拦截器中的this是指向minapp-api-promise实例本身)
155 | * @Author: bigmeow
156 | * @Date: 2018-03-26 15:59:42
157 | */
158 | export default{
159 | // 发出请求时的回调函数
160 | config (config) {
161 | // 请求前设置token
162 | const globalData = getApp().globalData
163 | if (globalData.auth && globalData.auth.token) {
164 | config.header = {
165 | Authorization: globalData.auth.token
166 | }
167 | }
168 | return config
169 | },
170 |
171 | // 请求成功后的回调函数
172 | async success (resp) {
173 | this.hideLoading()
174 | let errorMesg = ''
175 | // 可以在这里对收到的响应数据对象进行加工处理
176 | switch (resp.statusCode) {
177 | case 200:
178 | console.log('正常请求')
179 | break
180 | case 401:
181 | console.log('未登陆,拦截重定向登陆界面')
182 | await this.redirectTo({
183 | url: 'login'
184 | })
185 | break
186 | case 403:
187 | console.log('未授权接口,拦截')
188 | this.showModal({
189 | title: '警告',
190 | content: (resp.data.error && (resp.data.error.details || resp.data.error.message)) || '无权请联系管理员',
191 | confirmText: '我知道了',
192 | showCancel: false
193 | })
194 | throw new Error(errorMesg)
195 | case 500:
196 | case 502:
197 | errorMesg = (resp.data.error && (resp.data.error.details || resp.data.error.message)) || '服务器出错'
198 | break
199 | case 503:
200 | errorMesg = '哦~服务器宕机了'
201 | break
202 | }
203 | if (errorMesg.length > 0) {
204 | this.showToast({
205 | title: errorMesg,
206 | icon: 'none'
207 | })
208 | throw new Error(errorMesg)
209 | }
210 | return resp
211 | },
212 |
213 | fail (resp) {
214 | this.hideLoading()
215 | this.showToast({
216 | title: '网络连接失败',
217 | icon: 'none'
218 | })
219 | }
220 | }
221 |
222 | ```
223 |
224 | 页面.js引入
225 | ```js
226 | import wxp from 'minapp-api-promise'
227 | import requestIntercept from '相对目录/requestIntercept'
228 | // 注册请求拦截器
229 | wxp.intercept('request', requestIntercept)
230 | ```
231 |
232 | ### 注意
233 | - 某些古老设备不支持Promise对象,需要自行引入promise-polyfill库进行兼容;
234 | - 使用async/await语法糖,需要webpack配合babel插件将之转换成es5语法
235 |
236 |
--------------------------------------------------------------------------------
/src/core.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Tencent is pleased to support the open source community by making WePY available.
3 | * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
4 | *
5 | * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
6 | * http://opensource.org/licenses/MIT
7 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
8 | */
9 |
10 | let native = {};
11 | let RequestMQ = {
12 | map: {},
13 | mq: [],
14 | running: [],
15 | MAX_REQUEST: 10,
16 | push (param) {
17 | param.t = +new Date();
18 | while ((this.mq.indexOf(param.t) > -1 || this.running.indexOf(param.t) > -1)) {
19 | param.t += Math.random() * 10 >> 0;
20 | }
21 | this.mq.push(param.t);
22 | this.map[param.t] = param;
23 | },
24 | next () {
25 | let me = this;
26 |
27 | if (this.mq.length === 0)
28 | return;
29 |
30 | if (this.running.length < this.MAX_REQUEST - 1) {
31 | let newone = this.mq.shift();
32 | let obj = this.map[newone];
33 | let oldComplete = obj.complete;
34 | obj.complete = (...args) => {
35 | me.running.splice(me.running.indexOf(obj.t), 1);
36 | delete me.map[obj.t];
37 | oldComplete && oldComplete.apply(obj, args);
38 | me.next();
39 | }
40 | this.running.push(obj.t);
41 | return wx.request(obj);
42 | }
43 | },
44 | request (obj) {
45 |
46 | obj = obj || {};
47 | obj = (typeof(obj) === 'string') ? {url: obj} : obj;
48 |
49 |
50 | this.push(obj);
51 |
52 | return this.next();
53 | }
54 | };
55 |
56 |
57 | export default class CoreClass {
58 |
59 |
60 | constructor () {
61 | this.$addons = {};
62 |
63 | this.$interceptors = {};
64 | }
65 |
66 |
67 | $init (wepy, config = {}) {
68 | this.$initAPI(wepy, config.noPromiseAPI);
69 | }
70 |
71 |
72 | use (addon, ...args) {
73 | if (typeof(addon) === 'string' && this[addon]) {
74 | this.$addons[addon] = 1;
75 | this[addon](args);
76 | } else {
77 | this.$addons[addon.name] = new addon(args);
78 | }
79 | }
80 |
81 | intercept (api, provider) {
82 | this.$interceptors[api] = provider;
83 | }
84 |
85 | promisify () {
86 | console.log('promise已经启用')
87 | }
88 |
89 | requestfix () {
90 | console.log('requestfix启用')
91 | }
92 |
93 | $initAPI (wepy, noPromiseAPI) {
94 | const self = this;
95 | let noPromiseMethods = {
96 | // 媒体
97 | stopRecord: true,
98 | getRecorderManager: true,
99 | pauseVoice: true,
100 | stopVoice: true,
101 | pauseBackgroundAudio: true,
102 | stopBackgroundAudio: true,
103 | getBackgroundAudioManager: true,
104 | createAudioContext: true,
105 | createInnerAudioContext: true,
106 | createVideoContext: true,
107 | createCameraContext: true,
108 |
109 | // 位置
110 | createMapContext: true,
111 |
112 | // 设备
113 | canIUse: true,
114 | startAccelerometer: true,
115 | stopAccelerometer: true,
116 | startCompass: true,
117 | stopCompass: true,
118 | onBLECharacteristicValueChange: true,
119 | onBLEConnectionStateChange: true,
120 |
121 | // 界面
122 | hideToast: true,
123 | hideLoading: true,
124 | showNavigationBarLoading: true,
125 | hideNavigationBarLoading: true,
126 | navigateBack: true,
127 | createAnimation: true,
128 | pageScrollTo: true,
129 | createSelectorQuery: true,
130 | createCanvasContext: true,
131 | createContext: true,
132 | drawCanvas: true,
133 | hideKeyboard: true,
134 | stopPullDownRefresh: true,
135 |
136 | // 拓展接口
137 | arrayBufferToBase64: true,
138 | base64ToArrayBuffer: true
139 | };
140 | if (noPromiseAPI) {
141 | if (Array.isArray(noPromiseAPI)) {
142 | noPromiseAPI.forEach(v => noPromiseMethods[v] = true);
143 | } else {
144 | for (let k in noPromiseAPI) {
145 | noPromiseMethods[k] = noPromiseAPI[k];
146 | }
147 | }
148 | }
149 | Object.keys(wx).forEach((key) => {
150 | if (!noPromiseMethods[key] && key.substr(0, 2) !== 'on' && !(/\w+Sync$/.test(key))) {
151 | Object.defineProperty(native, key, {
152 | get () {
153 | return (obj) => {
154 | obj = obj || {};
155 | if (self.$interceptors[key] && self.$interceptors[key].config) {
156 | let rst = self.$interceptors[key].config.call(self, obj);
157 | if (rst === false) {
158 | if (self.$addons.promisify) {
159 | return Promise.reject('aborted by interceptor');
160 | } else {
161 | obj.fail && obj.fail('aborted by interceptor');
162 | return;
163 | }
164 | }
165 | obj = rst;
166 | }
167 | if (key === 'request') {
168 | obj = (typeof(obj) === 'string') ? {url: obj} : obj;
169 | }
170 | if (typeof obj === 'string') {
171 | return wx[key](obj);
172 | }
173 | if (self.$addons.promisify) {
174 | let task;
175 | const p = new Promise((resolve, reject) => {
176 | let bak = {};
177 | ['fail', 'success', 'complete'].forEach((k) => {
178 | bak[k] = obj[k];
179 | obj[k] = (res) => {
180 | if (self.$interceptors[key] && self.$interceptors[key][k]) {
181 | res = self.$interceptors[key][k].call(self, res);
182 | }
183 | if (k === 'success')
184 | resolve(res);
185 | else if (k === 'fail')
186 | reject(res);
187 | };
188 | });
189 | if (self.$addons.requestfix && key === 'request') {
190 | RequestMQ.request(obj);
191 | } else {
192 | task = wx[key](obj);
193 | }
194 | });
195 | if (key === 'uploadFile' || key === 'downloadFile') {
196 | p.progress = (cb) => {
197 | task.onProgressUpdate(cb);
198 | return p;
199 | };
200 | p.abort = (cb) => {
201 | cb && cb();
202 | task.abort();
203 | return p;
204 | }
205 | }
206 | return p;
207 | } else {
208 | let bak = {};
209 | ['fail', 'success', 'complete'].forEach((k) => {
210 | bak[k] = obj[k];
211 | obj[k] = (res) => {
212 | if (self.$interceptors[key] && self.$interceptors[key][k]) {
213 | res = self.$interceptors[key][k].call(self, res);
214 | }
215 | bak[k] && bak[k].call(self, res);
216 | };
217 | });
218 | if (self.$addons.requestfix && key === 'request') {
219 | RequestMQ.request(obj);
220 | } else {
221 | return wx[key](obj);
222 | }
223 | }
224 | };
225 | }
226 | });
227 | wepy[key] = native[key];
228 | } else {
229 | Object.defineProperty(native, key, {
230 | get () { return (...args) => wx[key].apply(wx, args) }
231 | });
232 | wepy[key] = native[key];
233 | }
234 | });
235 |
236 | }
237 | }
--------------------------------------------------------------------------------
/dist/wxp.js:
--------------------------------------------------------------------------------
1 | (function webpackUniversalModuleDefinition(root, factory) {
2 | if(typeof exports === 'object' && typeof module === 'object')
3 | module.exports = factory();
4 | else if(typeof define === 'function' && define.amd)
5 | define([], factory);
6 | else {
7 | var a = factory();
8 | for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
9 | }
10 | })(window, function() {
11 | return /******/ (function(modules) { // webpackBootstrap
12 | /******/ // The module cache
13 | /******/ var installedModules = {};
14 | /******/
15 | /******/ // The require function
16 | /******/ function __webpack_require__(moduleId) {
17 | /******/
18 | /******/ // Check if module is in cache
19 | /******/ if(installedModules[moduleId]) {
20 | /******/ return installedModules[moduleId].exports;
21 | /******/ }
22 | /******/ // Create a new module (and put it into the cache)
23 | /******/ var module = installedModules[moduleId] = {
24 | /******/ i: moduleId,
25 | /******/ l: false,
26 | /******/ exports: {}
27 | /******/ };
28 | /******/
29 | /******/ // Execute the module function
30 | /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
31 | /******/
32 | /******/ // Flag the module as loaded
33 | /******/ module.l = true;
34 | /******/
35 | /******/ // Return the exports of the module
36 | /******/ return module.exports;
37 | /******/ }
38 | /******/
39 | /******/
40 | /******/ // expose the modules object (__webpack_modules__)
41 | /******/ __webpack_require__.m = modules;
42 | /******/
43 | /******/ // expose the module cache
44 | /******/ __webpack_require__.c = installedModules;
45 | /******/
46 | /******/ // define getter function for harmony exports
47 | /******/ __webpack_require__.d = function(exports, name, getter) {
48 | /******/ if(!__webpack_require__.o(exports, name)) {
49 | /******/ Object.defineProperty(exports, name, {
50 | /******/ configurable: false,
51 | /******/ enumerable: true,
52 | /******/ get: getter
53 | /******/ });
54 | /******/ }
55 | /******/ };
56 | /******/
57 | /******/ // define __esModule on exports
58 | /******/ __webpack_require__.r = function(exports) {
59 | /******/ Object.defineProperty(exports, '__esModule', { value: true });
60 | /******/ };
61 | /******/
62 | /******/ // getDefaultExport function for compatibility with non-harmony modules
63 | /******/ __webpack_require__.n = function(module) {
64 | /******/ var getter = module && module.__esModule ?
65 | /******/ function getDefault() { return module['default']; } :
66 | /******/ function getModuleExports() { return module; };
67 | /******/ __webpack_require__.d(getter, 'a', getter);
68 | /******/ return getter;
69 | /******/ };
70 | /******/
71 | /******/ // Object.prototype.hasOwnProperty.call
72 | /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
73 | /******/
74 | /******/ // __webpack_public_path__
75 | /******/ __webpack_require__.p = "";
76 | /******/
77 | /******/
78 | /******/ // Load entry module and return exports
79 | /******/ return __webpack_require__(__webpack_require__.s = 0);
80 | /******/ })
81 | /************************************************************************/
82 | /******/ ([
83 | /* 0 */
84 | /***/ (function(module, __webpack_exports__, __webpack_require__) {
85 |
86 | "use strict";
87 | __webpack_require__.r(__webpack_exports__);
88 |
89 | // CONCATENATED MODULE: ./src/core.js
90 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
91 |
92 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
93 |
94 | /**
95 | * Tencent is pleased to support the open source community by making WePY available.
96 | * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
97 | *
98 | * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
99 | * http://opensource.org/licenses/MIT
100 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
101 | */
102 |
103 | var core_native = {};
104 | var RequestMQ = {
105 | map: {},
106 | mq: [],
107 | running: [],
108 | MAX_REQUEST: 10,
109 | push: function push(param) {
110 | param.t = +new Date();
111 | while (this.mq.indexOf(param.t) > -1 || this.running.indexOf(param.t) > -1) {
112 | param.t += Math.random() * 10 >> 0;
113 | }
114 | this.mq.push(param.t);
115 | this.map[param.t] = param;
116 | },
117 | next: function next() {
118 | var me = this;
119 |
120 | if (this.mq.length === 0) return;
121 |
122 | if (this.running.length < this.MAX_REQUEST - 1) {
123 | var newone = this.mq.shift();
124 | var obj = this.map[newone];
125 | var oldComplete = obj.complete;
126 | obj.complete = function () {
127 | for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
128 | args[_key] = arguments[_key];
129 | }
130 |
131 | me.running.splice(me.running.indexOf(obj.t), 1);
132 | delete me.map[obj.t];
133 | oldComplete && oldComplete.apply(obj, args);
134 | me.next();
135 | };
136 | this.running.push(obj.t);
137 | return wx.request(obj);
138 | }
139 | },
140 | request: function request(obj) {
141 |
142 | obj = obj || {};
143 | obj = typeof obj === 'string' ? { url: obj } : obj;
144 |
145 | this.push(obj);
146 |
147 | return this.next();
148 | }
149 | };
150 |
151 | var CoreClass = function () {
152 | function CoreClass() {
153 | _classCallCheck(this, CoreClass);
154 |
155 | this.$addons = {};
156 |
157 | this.$interceptors = {};
158 | }
159 |
160 | _createClass(CoreClass, [{
161 | key: '$init',
162 | value: function $init(wepy) {
163 | var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
164 |
165 | this.$initAPI(wepy, config.noPromiseAPI);
166 | }
167 | }, {
168 | key: 'use',
169 | value: function use(addon) {
170 | for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
171 | args[_key2 - 1] = arguments[_key2];
172 | }
173 |
174 | if (typeof addon === 'string' && this[addon]) {
175 | this.$addons[addon] = 1;
176 | this[addon](args);
177 | } else {
178 | this.$addons[addon.name] = new addon(args);
179 | }
180 | }
181 | }, {
182 | key: 'intercept',
183 | value: function intercept(api, provider) {
184 | this.$interceptors[api] = provider;
185 | }
186 | }, {
187 | key: 'promisify',
188 | value: function promisify() {
189 | console.log('promise已经启用');
190 | }
191 | }, {
192 | key: 'requestfix',
193 | value: function requestfix() {
194 | console.log('requestfix启用');
195 | }
196 | }, {
197 | key: '$initAPI',
198 | value: function $initAPI(wepy, noPromiseAPI) {
199 | var self = this;
200 | var noPromiseMethods = {
201 | // 媒体
202 | stopRecord: true,
203 | getRecorderManager: true,
204 | pauseVoice: true,
205 | stopVoice: true,
206 | pauseBackgroundAudio: true,
207 | stopBackgroundAudio: true,
208 | getBackgroundAudioManager: true,
209 | createAudioContext: true,
210 | createInnerAudioContext: true,
211 | createVideoContext: true,
212 | createCameraContext: true,
213 |
214 | // 位置
215 | createMapContext: true,
216 |
217 | // 设备
218 | canIUse: true,
219 | startAccelerometer: true,
220 | stopAccelerometer: true,
221 | startCompass: true,
222 | stopCompass: true,
223 | onBLECharacteristicValueChange: true,
224 | onBLEConnectionStateChange: true,
225 |
226 | // 界面
227 | hideToast: true,
228 | hideLoading: true,
229 | showNavigationBarLoading: true,
230 | hideNavigationBarLoading: true,
231 | navigateBack: true,
232 | createAnimation: true,
233 | pageScrollTo: true,
234 | createSelectorQuery: true,
235 | createCanvasContext: true,
236 | createContext: true,
237 | drawCanvas: true,
238 | hideKeyboard: true,
239 | stopPullDownRefresh: true,
240 |
241 | // 拓展接口
242 | arrayBufferToBase64: true,
243 | base64ToArrayBuffer: true
244 | };
245 | if (noPromiseAPI) {
246 | if (Array.isArray(noPromiseAPI)) {
247 | noPromiseAPI.forEach(function (v) {
248 | return noPromiseMethods[v] = true;
249 | });
250 | } else {
251 | for (var k in noPromiseAPI) {
252 | noPromiseMethods[k] = noPromiseAPI[k];
253 | }
254 | }
255 | }
256 | Object.keys(wx).forEach(function (key) {
257 | if (!noPromiseMethods[key] && key.substr(0, 2) !== 'on' && !/\w+Sync$/.test(key)) {
258 | Object.defineProperty(core_native, key, {
259 | get: function get() {
260 | return function (obj) {
261 | obj = obj || {};
262 | if (self.$interceptors[key] && self.$interceptors[key].config) {
263 | var rst = self.$interceptors[key].config.call(self, obj);
264 | if (rst === false) {
265 | if (self.$addons.promisify) {
266 | return Promise.reject('aborted by interceptor');
267 | } else {
268 | obj.fail && obj.fail('aborted by interceptor');
269 | return;
270 | }
271 | }
272 | obj = rst;
273 | }
274 | if (key === 'request') {
275 | obj = typeof obj === 'string' ? { url: obj } : obj;
276 | }
277 | if (typeof obj === 'string') {
278 | return wx[key](obj);
279 | }
280 | if (self.$addons.promisify) {
281 | var task = void 0;
282 | var p = new Promise(function (resolve, reject) {
283 | var bak = {};
284 | ['fail', 'success', 'complete'].forEach(function (k) {
285 | bak[k] = obj[k];
286 | obj[k] = function (res) {
287 | if (self.$interceptors[key] && self.$interceptors[key][k]) {
288 | res = self.$interceptors[key][k].call(self, res);
289 | }
290 | if (k === 'success') resolve(res);else if (k === 'fail') reject(res);
291 | };
292 | });
293 | if (self.$addons.requestfix && key === 'request') {
294 | RequestMQ.request(obj);
295 | } else {
296 | task = wx[key](obj);
297 | }
298 | });
299 | if (key === 'uploadFile' || key === 'downloadFile') {
300 | p.progress = function (cb) {
301 | task.onProgressUpdate(cb);
302 | return p;
303 | };
304 | p.abort = function (cb) {
305 | cb && cb();
306 | task.abort();
307 | return p;
308 | };
309 | }
310 | return p;
311 | } else {
312 | var bak = {};
313 | ['fail', 'success', 'complete'].forEach(function (k) {
314 | bak[k] = obj[k];
315 | obj[k] = function (res) {
316 | if (self.$interceptors[key] && self.$interceptors[key][k]) {
317 | res = self.$interceptors[key][k].call(self, res);
318 | }
319 | bak[k] && bak[k].call(self, res);
320 | };
321 | });
322 | if (self.$addons.requestfix && key === 'request') {
323 | RequestMQ.request(obj);
324 | } else {
325 | return wx[key](obj);
326 | }
327 | }
328 | };
329 | }
330 | });
331 | wepy[key] = core_native[key];
332 | } else {
333 | Object.defineProperty(core_native, key, {
334 | get: function get() {
335 | return function () {
336 | for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
337 | args[_key3] = arguments[_key3];
338 | }
339 |
340 | return wx[key].apply(wx, args);
341 | };
342 | }
343 | });
344 | wepy[key] = core_native[key];
345 | }
346 | });
347 | }
348 | }]);
349 |
350 | return CoreClass;
351 | }();
352 |
353 | /* harmony default export */ var core = (CoreClass);
354 | // CONCATENATED MODULE: ./src/wxp.js
355 |
356 | var wxp_wxp = new core();
357 | wxp_wxp.$init(wxp_wxp);
358 | wxp_wxp.use('promisify');
359 | wxp_wxp.use('requestfix');
360 | /* harmony default export */ var src_wxp = __webpack_exports__["default"] = (wxp_wxp);
361 |
362 | /***/ })
363 | /******/ ]);
364 | });
--------------------------------------------------------------------------------
/demo/demo1/lib/wxp.js:
--------------------------------------------------------------------------------
1 | (function webpackUniversalModuleDefinition(root, factory) {
2 | if(typeof exports === 'object' && typeof module === 'object')
3 | module.exports = factory();
4 | else if(typeof define === 'function' && define.amd)
5 | define([], factory);
6 | else {
7 | var a = factory();
8 | for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
9 | }
10 | })(window, function() {
11 | return /******/ (function(modules) { // webpackBootstrap
12 | /******/ // The module cache
13 | /******/ var installedModules = {};
14 | /******/
15 | /******/ // The require function
16 | /******/ function __webpack_require__(moduleId) {
17 | /******/
18 | /******/ // Check if module is in cache
19 | /******/ if(installedModules[moduleId]) {
20 | /******/ return installedModules[moduleId].exports;
21 | /******/ }
22 | /******/ // Create a new module (and put it into the cache)
23 | /******/ var module = installedModules[moduleId] = {
24 | /******/ i: moduleId,
25 | /******/ l: false,
26 | /******/ exports: {}
27 | /******/ };
28 | /******/
29 | /******/ // Execute the module function
30 | /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
31 | /******/
32 | /******/ // Flag the module as loaded
33 | /******/ module.l = true;
34 | /******/
35 | /******/ // Return the exports of the module
36 | /******/ return module.exports;
37 | /******/ }
38 | /******/
39 | /******/
40 | /******/ // expose the modules object (__webpack_modules__)
41 | /******/ __webpack_require__.m = modules;
42 | /******/
43 | /******/ // expose the module cache
44 | /******/ __webpack_require__.c = installedModules;
45 | /******/
46 | /******/ // define getter function for harmony exports
47 | /******/ __webpack_require__.d = function(exports, name, getter) {
48 | /******/ if(!__webpack_require__.o(exports, name)) {
49 | /******/ Object.defineProperty(exports, name, {
50 | /******/ configurable: false,
51 | /******/ enumerable: true,
52 | /******/ get: getter
53 | /******/ });
54 | /******/ }
55 | /******/ };
56 | /******/
57 | /******/ // define __esModule on exports
58 | /******/ __webpack_require__.r = function(exports) {
59 | /******/ Object.defineProperty(exports, '__esModule', { value: true });
60 | /******/ };
61 | /******/
62 | /******/ // getDefaultExport function for compatibility with non-harmony modules
63 | /******/ __webpack_require__.n = function(module) {
64 | /******/ var getter = module && module.__esModule ?
65 | /******/ function getDefault() { return module['default']; } :
66 | /******/ function getModuleExports() { return module; };
67 | /******/ __webpack_require__.d(getter, 'a', getter);
68 | /******/ return getter;
69 | /******/ };
70 | /******/
71 | /******/ // Object.prototype.hasOwnProperty.call
72 | /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
73 | /******/
74 | /******/ // __webpack_public_path__
75 | /******/ __webpack_require__.p = "";
76 | /******/
77 | /******/
78 | /******/ // Load entry module and return exports
79 | /******/ return __webpack_require__(__webpack_require__.s = 0);
80 | /******/ })
81 | /************************************************************************/
82 | /******/ ([
83 | /* 0 */
84 | /***/ (function(module, __webpack_exports__, __webpack_require__) {
85 |
86 | "use strict";
87 | __webpack_require__.r(__webpack_exports__);
88 |
89 | // CONCATENATED MODULE: ./src/core.js
90 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
91 |
92 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
93 |
94 | /**
95 | * Tencent is pleased to support the open source community by making WePY available.
96 | * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
97 | *
98 | * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
99 | * http://opensource.org/licenses/MIT
100 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
101 | */
102 |
103 | var core_native = {};
104 | var RequestMQ = {
105 | map: {},
106 | mq: [],
107 | running: [],
108 | MAX_REQUEST: 5,
109 | push: function push(param) {
110 | param.t = +new Date();
111 | while (this.mq.indexOf(param.t) > -1 || this.running.indexOf(param.t) > -1) {
112 | param.t += Math.random() * 10 >> 0;
113 | }
114 | this.mq.push(param.t);
115 | this.map[param.t] = param;
116 | },
117 | next: function next() {
118 | var me = this;
119 |
120 | if (this.mq.length === 0) return;
121 |
122 | if (this.running.length < this.MAX_REQUEST - 1) {
123 | var newone = this.mq.shift();
124 | var obj = this.map[newone];
125 | var oldComplete = obj.complete;
126 | obj.complete = function () {
127 | for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
128 | args[_key] = arguments[_key];
129 | }
130 |
131 | me.running.splice(me.running.indexOf(obj.t), 1);
132 | delete me.map[obj.t];
133 | oldComplete && oldComplete.apply(obj, args);
134 | me.next();
135 | };
136 | this.running.push(obj.t);
137 | return wx.request(obj);
138 | }
139 | },
140 | request: function request(obj) {
141 |
142 | obj = obj || {};
143 | obj = typeof obj === 'string' ? { url: obj } : obj;
144 |
145 | this.push(obj);
146 |
147 | return this.next();
148 | }
149 | };
150 |
151 | var CoreClass = function () {
152 | function CoreClass() {
153 | _classCallCheck(this, CoreClass);
154 |
155 | this.$addons = {};
156 |
157 | this.$interceptors = {};
158 |
159 | this.$pages = {};
160 | }
161 |
162 | _createClass(CoreClass, [{
163 | key: '$init',
164 | value: function $init(wepy) {
165 | var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
166 |
167 | this.$initAPI(wepy, config.noPromiseAPI);
168 | this.$wxapp = getApp();
169 | }
170 | }, {
171 | key: 'use',
172 | value: function use(addon) {
173 | for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
174 | args[_key2 - 1] = arguments[_key2];
175 | }
176 |
177 | if (typeof addon === 'string' && this[addon]) {
178 | this.$addons[addon] = 1;
179 | this[addon](args);
180 | } else {
181 | this.$addons[addon.name] = new addon(args);
182 | }
183 | }
184 | }, {
185 | key: 'intercept',
186 | value: function intercept(api, provider) {
187 | this.$interceptors[api] = provider;
188 | }
189 | }, {
190 | key: 'promisify',
191 | value: function promisify() {
192 | console.log('promise已经启用');
193 | }
194 | }, {
195 | key: 'requestfix',
196 | value: function requestfix() {
197 | console.log('requestfix启用');
198 | }
199 | }, {
200 | key: '$initAPI',
201 | value: function $initAPI(wepy, noPromiseAPI) {
202 | var self = this;
203 | var noPromiseMethods = {
204 | // 媒体
205 | stopRecord: true,
206 | getRecorderManager: true,
207 | pauseVoice: true,
208 | stopVoice: true,
209 | pauseBackgroundAudio: true,
210 | stopBackgroundAudio: true,
211 | getBackgroundAudioManager: true,
212 | createAudioContext: true,
213 | createInnerAudioContext: true,
214 | createVideoContext: true,
215 | createCameraContext: true,
216 |
217 | // 位置
218 | createMapContext: true,
219 |
220 | // 设备
221 | canIUse: true,
222 | startAccelerometer: true,
223 | stopAccelerometer: true,
224 | startCompass: true,
225 | stopCompass: true,
226 | onBLECharacteristicValueChange: true,
227 | onBLEConnectionStateChange: true,
228 |
229 | // 界面
230 | hideToast: true,
231 | hideLoading: true,
232 | showNavigationBarLoading: true,
233 | hideNavigationBarLoading: true,
234 | navigateBack: true,
235 | createAnimation: true,
236 | pageScrollTo: true,
237 | createSelectorQuery: true,
238 | createCanvasContext: true,
239 | createContext: true,
240 | drawCanvas: true,
241 | hideKeyboard: true,
242 | stopPullDownRefresh: true,
243 |
244 | // 拓展接口
245 | arrayBufferToBase64: true,
246 | base64ToArrayBuffer: true
247 | };
248 | if (noPromiseAPI) {
249 | if (Array.isArray(noPromiseAPI)) {
250 | noPromiseAPI.forEach(function (v) {
251 | return noPromiseMethods[v] = true;
252 | });
253 | } else {
254 | for (var k in noPromiseAPI) {
255 | noPromiseMethods[k] = noPromiseAPI[k];
256 | }
257 | }
258 | }
259 | Object.keys(wx).forEach(function (key) {
260 | if (!noPromiseMethods[key] && key.substr(0, 2) !== 'on' && !/\w+Sync$/.test(key)) {
261 | Object.defineProperty(core_native, key, {
262 | get: function get() {
263 | return function (obj) {
264 | obj = obj || {};
265 | if (self.$interceptors[key] && self.$interceptors[key].config) {
266 | var rst = self.$interceptors[key].config.call(self, obj);
267 | if (rst === false) {
268 | if (self.$addons.promisify) {
269 | return Promise.reject('aborted by interceptor');
270 | } else {
271 | obj.fail && obj.fail('aborted by interceptor');
272 | return;
273 | }
274 | }
275 | obj = rst;
276 | }
277 | if (key === 'request') {
278 | obj = typeof obj === 'string' ? { url: obj } : obj;
279 | }
280 | if (typeof obj === 'string') {
281 | return wx[key](obj);
282 | }
283 | if (self.$addons.promisify) {
284 | var task = void 0;
285 | var p = new Promise(function (resolve, reject) {
286 | var bak = {};
287 | ['fail', 'success', 'complete'].forEach(function (k) {
288 | bak[k] = obj[k];
289 | obj[k] = function (res) {
290 | if (self.$interceptors[key] && self.$interceptors[key][k]) {
291 | res = self.$interceptors[key][k].call(self, res);
292 | }
293 | if (k === 'success') resolve(res);else if (k === 'fail') reject(res);
294 | };
295 | });
296 | if (self.$addons.requestfix && key === 'request') {
297 | RequestMQ.request(obj);
298 | } else {
299 | task = wx[key](obj);
300 | }
301 | });
302 | if (key === 'uploadFile' || key === 'downloadFile') {
303 | p.progress = function (cb) {
304 | task.onProgressUpdate(cb);
305 | return p;
306 | };
307 | p.abort = function (cb) {
308 | cb && cb();
309 | task.abort();
310 | return p;
311 | };
312 | }
313 | return p;
314 | } else {
315 | var bak = {};
316 | ['fail', 'success', 'complete'].forEach(function (k) {
317 | bak[k] = obj[k];
318 | obj[k] = function (res) {
319 | if (self.$interceptors[key] && self.$interceptors[key][k]) {
320 | res = self.$interceptors[key][k].call(self, res);
321 | }
322 | bak[k] && bak[k].call(self, res);
323 | };
324 | });
325 | if (self.$addons.requestfix && key === 'request') {
326 | RequestMQ.request(obj);
327 | } else {
328 | return wx[key](obj);
329 | }
330 | }
331 | };
332 | }
333 | });
334 | wepy[key] = core_native[key];
335 | } else {
336 | Object.defineProperty(core_native, key, {
337 | get: function get() {
338 | return function () {
339 | for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
340 | args[_key3] = arguments[_key3];
341 | }
342 |
343 | return wx[key].apply(wx, args);
344 | };
345 | }
346 | });
347 | wepy[key] = core_native[key];
348 | }
349 | });
350 | }
351 | }]);
352 |
353 | return CoreClass;
354 | }();
355 |
356 | /* harmony default export */ var core = (CoreClass);
357 | // CONCATENATED MODULE: ./src/wxp.js
358 |
359 | var wxp_wxp = new core();
360 | wxp_wxp.$init(wxp_wxp);
361 | wxp_wxp.use('promisify');
362 | wxp_wxp.use('requestfix');
363 | /* harmony default export */ var src_wxp = __webpack_exports__["default"] = (wxp_wxp);
364 |
365 | /***/ })
366 | /******/ ]);
367 | });
--------------------------------------------------------------------------------