提交 4fb41fe8 编写于 作者: fxy060608's avatar fxy060608

refactor: defineApi

上级 48dba672
......@@ -11,20 +11,6 @@ import {
removeKeepAliveApiCallback,
} from './callback'
import { promisify } from './promise'
export const API_TYPE_ON = 0
export const API_TYPE_OFF = 1
export const API_TYPE_TASK = 2
export const API_TYPE_SYNC = 3
export const API_TYPE_ASYNC = 4
type API_TYPES =
| typeof API_TYPE_ON
| typeof API_TYPE_OFF
| typeof API_TYPE_TASK
| typeof API_TYPE_SYNC
| typeof API_TYPE_ASYNC
interface AsyncMethodOptionLike {
success?: (...args: any[]) => void
}
......@@ -131,17 +117,8 @@ function wrapperSyncApi(fn: Function) {
return (...args: any[]) => fn.apply(null, args)
}
function wrapperAsyncApi(
name: string,
fn: (args: unknown) => Promise<unknown>,
options?: ApiOptions
) {
return (args: Record<string, any>) => {
const id = createAsyncApiCallback(name, args, options)
fn(args)
.then((res) => invokeSuccess(id, name, res))
.catch((err) => invokeFail(id, name, err))
}
function wrapperAsyncApi(name: string, fn: Function, options?: ApiOptions) {
return wrapperTaskApi(name, fn, options)
}
function wrapperApi(
......@@ -166,10 +143,9 @@ export function defineOnApi<T extends Function>(
fn: () => void,
options?: ApiOptions
) {
return (defineApi(
API_TYPE_ON,
return (wrapperApi(
wrapperOnApi(name, fn),
name,
fn,
__DEV__ ? API_TYPE_ON_PROTOCOLS : undefined,
options
) as unknown) as T
......@@ -180,10 +156,9 @@ export function defineOffApi<T extends Function>(
fn: () => void,
options?: ApiOptions
) {
return (defineApi(
API_TYPE_OFF,
return (wrapperApi(
wrapperOffApi(name, fn),
name,
fn,
__DEV__ ? API_TYPE_ON_PROTOCOLS : undefined,
options
) as unknown) as T
......@@ -194,7 +169,7 @@ export function defineTaskApi<T extends TaskApiLike, P = AsyncApiOptions<T>>(
fn: (
args: Omit<P, 'success' | 'fail' | 'complete'>,
res: {
resolve: (res: AsyncApiRes<P>) => void
resolve: (res?: AsyncApiRes<P>) => void
reject: (err?: string) => void
}
) => ReturnType<T>,
......@@ -202,7 +177,12 @@ export function defineTaskApi<T extends TaskApiLike, P = AsyncApiOptions<T>>(
options?: ApiOptions
) {
return (promisify(
defineApi(API_TYPE_TASK, name, fn, __DEV__ ? protocol : undefined, options)
wrapperApi(
wrapperTaskApi(name, fn),
name,
__DEV__ ? protocol : undefined,
options
)
) as unknown) as T
}
......@@ -212,10 +192,9 @@ export function defineSyncApi<T extends Function>(
protocol?: ApiProtocols,
options?: ApiOptions
) {
return (defineApi(
API_TYPE_SYNC,
return (wrapperApi(
wrapperSyncApi(fn),
name,
fn,
__DEV__ ? protocol : undefined,
options
) as unknown) as T
......@@ -224,38 +203,21 @@ export function defineSyncApi<T extends Function>(
export function defineAsyncApi<T extends AsyncApiLike, P = AsyncApiOptions<T>>(
name: string,
fn: (
args: Omit<P, 'success' | 'fail' | 'complete'>
) => Promise<AsyncApiRes<P> | void>,
args: Omit<P, 'success' | 'fail' | 'complete'>,
res: {
resolve: (res?: AsyncApiRes<P>) => void
reject: (err?: string) => void
}
) => void,
protocol?: ApiProtocols,
options?: ApiOptions
) {
return promisify(
defineApi(API_TYPE_ASYNC, name, fn, __DEV__ ? protocol : undefined, options)
wrapperApi(
wrapperAsyncApi(name, fn as any, options),
name,
__DEV__ ? protocol : undefined,
options
)
) as AsyncApi<P>
}
function defineApi(
type: API_TYPES,
name: string,
fn: Function,
protocol?: ApiProtocols,
options?: ApiOptions
) {
switch (type) {
case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol, options)
case API_TYPE_OFF:
return wrapperApi(wrapperOffApi(name, fn), name, protocol, options)
case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol, options)
case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol, options)
case API_TYPE_ASYNC:
return wrapperApi(
wrapperAsyncApi(name, fn as any, options),
name,
protocol,
options
)
}
}
......@@ -7779,11 +7779,6 @@ function promisify(fn) {
}));
};
}
const API_TYPE_ON = 0;
const API_TYPE_OFF = 1;
const API_TYPE_TASK = 2;
const API_TYPE_SYNC = 3;
const API_TYPE_ASYNC = 4;
function formatApiArgs(args, options) {
const params = args[0];
if (!options || !isPlainObject(options.formatArgs) && isPlainObject(params)) {
......@@ -7835,10 +7830,7 @@ function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args);
}
function wrapperAsyncApi(name, fn, options) {
return (args) => {
const id2 = createAsyncApiCallback(name, args, options);
fn(args).then((res) => invokeSuccess(id2, name, res)).catch((err) => invokeFail(id2, name, err));
};
return wrapperTaskApi(name, fn, options);
}
function wrapperApi(fn, name, protocol, options) {
return function(...args) {
......@@ -7852,33 +7844,19 @@ function wrapperApi(fn, name, protocol, options) {
};
}
function defineOnApi(name, fn, options) {
return defineApi(API_TYPE_ON, name, fn, process.env.NODE_ENV !== "production" ? API_TYPE_ON_PROTOCOLS : void 0, options);
return wrapperApi(wrapperOnApi(name, fn), name, process.env.NODE_ENV !== "production" ? API_TYPE_ON_PROTOCOLS : void 0, options);
}
function defineOffApi(name, fn, options) {
return defineApi(API_TYPE_OFF, name, fn, process.env.NODE_ENV !== "production" ? API_TYPE_ON_PROTOCOLS : void 0, options);
return wrapperApi(wrapperOffApi(name, fn), name, process.env.NODE_ENV !== "production" ? API_TYPE_ON_PROTOCOLS : void 0, options);
}
function defineTaskApi(name, fn, protocol, options) {
return promisify(defineApi(API_TYPE_TASK, name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options));
return promisify(wrapperApi(wrapperTaskApi(name, fn), name, process.env.NODE_ENV !== "production" ? protocol : void 0, options));
}
function defineSyncApi(name, fn, protocol, options) {
return defineApi(API_TYPE_SYNC, name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options);
return wrapperApi(wrapperSyncApi(fn), name, process.env.NODE_ENV !== "production" ? protocol : void 0, options);
}
function defineAsyncApi(name, fn, protocol, options) {
return promisify(defineApi(API_TYPE_ASYNC, name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options));
}
function defineApi(type, name, fn, protocol, options) {
switch (type) {
case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol, options);
case API_TYPE_OFF:
return wrapperApi(wrapperOffApi(name, fn), name, protocol, options);
case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol, options);
case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol, options);
case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol, options);
}
return promisify(wrapperApi(wrapperAsyncApi(name, fn, options), name, process.env.NODE_ENV !== "production" ? protocol : void 0, options));
}
const API_BASE64_TO_ARRAY_BUFFER = "base64ToArrayBuffer";
const API_ARRAY_BUFFER_TO_BASE64 = "arrayBufferToBase64";
......@@ -8419,9 +8397,9 @@ const canIUse = defineSyncApi(API_CAN_I_USE, (schema) => {
}
return true;
}, CanIUseProtocol);
const makePhoneCall = defineAsyncApi(API_MAKE_PHONE_CALL, ({phoneNumber}) => {
const makePhoneCall = defineAsyncApi(API_MAKE_PHONE_CALL, ({phoneNumber}, {resolve}) => {
window.location.href = `tel:${phoneNumber}`;
return Promise.resolve();
return resolve();
}, MakePhoneCallProtocol);
const getSystemInfoSync = defineSyncApi("getSystemInfoSync", () => {
const pixelRatio2 = window.devicePixelRatio;
......@@ -8523,8 +8501,8 @@ const getSystemInfoSync = defineSyncApi("getSystemInfoSync", () => {
}
};
});
const getSystemInfo = defineAsyncApi("getSystemInfo", () => {
return Promise.resolve(getSystemInfoSync());
const getSystemInfo = defineAsyncApi("getSystemInfo", (_args, {resolve}) => {
return resolve(getSystemInfoSync());
});
const API_ON_NETWORK_STATUS_CHANGE = "onNetworkStatusChange";
function networkListener() {
......@@ -8556,7 +8534,7 @@ const offNetworkStatusChange = defineOffApi("offNetworkStatusChange", () => {
window.removeEventListener("online", networkListener);
}
});
const getNetworkType = defineAsyncApi("getNetworkType", () => {
const getNetworkType = defineAsyncApi("getNetworkType", (_args, {resolve}) => {
const connection = getConnection();
let networkType = "unknown";
if (connection) {
......@@ -8569,30 +8547,28 @@ const getNetworkType = defineAsyncApi("getNetworkType", () => {
} else if (navigator.onLine === false) {
networkType = "none";
}
return Promise.resolve({networkType});
return resolve({networkType});
});
const openDocument = defineAsyncApi(API_OPEN_DOCUMENT, ({filePath}) => {
const openDocument = defineAsyncApi(API_OPEN_DOCUMENT, ({filePath}, {resolve}) => {
window.open(filePath);
return Promise.resolve();
return resolve();
}, OpenDocumentProtocol);
function _getServiceAddress() {
return window.location.protocol + "//" + window.location.host;
}
const getImageInfo = defineAsyncApi(API_GET_IMAGE_INFO, ({src}) => {
const getImageInfo = defineAsyncApi(API_GET_IMAGE_INFO, ({src}, {resolve, reject}) => {
const img = new Image();
return new Promise((resolve, reject) => {
img.onload = function() {
resolve({
width: img.naturalWidth,
height: img.naturalHeight,
path: src.indexOf("/") === 0 ? _getServiceAddress() + src : src
});
};
img.onerror = function() {
reject();
};
img.src = src;
});
img.onload = function() {
resolve({
width: img.naturalWidth,
height: img.naturalHeight,
path: src.indexOf("/") === 0 ? _getServiceAddress() + src : src
});
};
img.onerror = function() {
reject();
};
img.src = src;
}, GetImageInfoProtocol, GetImageInfoOptions);
const request = defineTaskApi(API_REQUEST, ({
url,
......@@ -8713,7 +8689,7 @@ function parseHeaders(headers) {
});
return headersObject;
}
const navigateBack = defineAsyncApi(API_NAVIGATE_BACK, ({delta}) => new Promise((resolve, reject) => {
const navigateBack = defineAsyncApi(API_NAVIGATE_BACK, ({delta}, {resolve, reject}) => {
let canBack = true;
const vm = getCurrentPageVm();
if (vm && vm.$callHook("onBackPress") === true) {
......@@ -8723,8 +8699,8 @@ const navigateBack = defineAsyncApi(API_NAVIGATE_BACK, ({delta}) => new Promise(
return reject("onBackPress");
}
getApp().$router.go(-delta);
resolve();
}), NavigateBackProtocol, NavigateBackOptions);
return resolve();
}, NavigateBackProtocol, NavigateBackOptions);
function navigate(type, url) {
const router = getApp().$router;
return new Promise((resolve, reject) => {
......@@ -8740,10 +8716,10 @@ function navigate(type, url) {
});
});
}
const navigateTo = defineAsyncApi(API_NAVIGATE_TO, ({url}) => navigate(API_NAVIGATE_TO, url), NavigateToProtocol, NavigateToOptions);
const redirectTo = defineAsyncApi(API_REDIRECT_TO, ({url}) => navigate(API_REDIRECT_TO, url), RedirectToProtocol, RedirectToOptions);
const reLaunch = defineAsyncApi(API_RE_LAUNCH, ({url}) => navigate(API_RE_LAUNCH, url), ReLaunchProtocol, ReLaunchOptions);
const switchTab = defineAsyncApi(API_SWITCH_TAB, ({url}) => navigate(API_SWITCH_TAB, url), SwitchTabProtocol, SwitchTabOptions);
const navigateTo = defineAsyncApi(API_NAVIGATE_TO, ({url}, {resolve, reject}) => navigate(API_NAVIGATE_TO, url).then(resolve).catch(reject), NavigateToProtocol, NavigateToOptions);
const redirectTo = defineAsyncApi(API_REDIRECT_TO, ({url}, {resolve, reject}) => navigate(API_REDIRECT_TO, url).then(resolve).catch(reject), RedirectToProtocol, RedirectToOptions);
const reLaunch = defineAsyncApi(API_RE_LAUNCH, ({url}, {resolve, reject}) => navigate(API_RE_LAUNCH, url).then(resolve).catch(reject), ReLaunchProtocol, ReLaunchOptions);
const switchTab = defineAsyncApi(API_SWITCH_TAB, ({url}, {resolve, reject}) => navigate(API_SWITCH_TAB, url).then(resolve).catch(reject), SwitchTabProtocol, SwitchTabOptions);
var api = /* @__PURE__ */ Object.freeze({
__proto__: null,
[Symbol.toStringTag]: "Module",
......
......@@ -4,7 +4,7 @@ import { getSystemInfoSync } from './getSystemInfoSync'
export const getSystemInfo = defineAsyncApi<typeof uni.getSystemInfo>(
'getSystemInfo',
() => {
return Promise.resolve(getSystemInfoSync())
(_args, { resolve }) => {
return resolve(getSystemInfoSync())
}
)
......@@ -6,9 +6,9 @@ import {
export const makePhoneCall = defineAsyncApi<typeof uni.makePhoneCall>(
API_MAKE_PHONE_CALL,
({ phoneNumber }) => {
({ phoneNumber }, { resolve }) => {
window.location.href = `tel:${phoneNumber}`
return Promise.resolve()
return resolve()
},
MakePhoneCallProtocol
)
......@@ -51,7 +51,7 @@ export const offNetworkStatusChange = defineOffApi<
export const getNetworkType = defineAsyncApi<typeof uni.getNetworkType>(
'getNetworkType',
() => {
(_args, { resolve }) => {
const connection = getConnection()
let networkType = 'unknown'
if (connection) {
......@@ -64,6 +64,6 @@ export const getNetworkType = defineAsyncApi<typeof uni.getNetworkType>(
} else if (navigator.onLine === false) {
networkType = 'none'
}
return Promise.resolve({ networkType })
return resolve({ networkType })
}
)
......@@ -6,9 +6,9 @@ import {
export const openDocument = defineAsyncApi<typeof uni.openDocument>(
API_OPEN_DOCUMENT,
({ filePath }) => {
({ filePath }, { resolve }) => {
window.open(filePath)
return Promise.resolve()
return resolve()
},
OpenDocumentProtocol
)
......@@ -11,21 +11,19 @@ function _getServiceAddress() {
export const getImageInfo = defineAsyncApi<typeof uni.getImageInfo>(
API_GET_IMAGE_INFO,
({ src }) => {
({ src }, { resolve, reject }) => {
const img = new Image()
return new Promise((resolve, reject) => {
img.onload = function () {
resolve({
width: img.naturalWidth,
height: img.naturalHeight,
path: src.indexOf('/') === 0 ? _getServiceAddress() + src : src,
} as UniApp.GetImageInfoSuccessData) // orientation和type是可选的,但GetImageInfoSuccessData定义的不对,暂时强制转换
}
img.onerror = function () {
reject()
}
img.src = src
})
img.onload = function () {
resolve({
width: img.naturalWidth,
height: img.naturalHeight,
path: src.indexOf('/') === 0 ? _getServiceAddress() + src : src,
} as UniApp.GetImageInfoSuccessData) // orientation和type是可选的,但GetImageInfoSuccessData定义的不对,暂时强制转换
}
img.onerror = function () {
reject()
}
img.src = src
},
GetImageInfoProtocol,
GetImageInfoOptions
......
......@@ -8,19 +8,18 @@ import {
export const navigateBack = defineAsyncApi<typeof uni.navigateBack>(
API_NAVIGATE_BACK,
({ delta }) =>
new Promise((resolve, reject) => {
let canBack = true
const vm = getCurrentPageVm()
if (vm && vm.$callHook('onBackPress') === true) {
canBack = false
}
if (!canBack) {
return reject('onBackPress')
}
getApp().$router.go(-delta!)
resolve()
}),
({ delta }, { resolve, reject }) => {
let canBack = true
const vm = getCurrentPageVm()
if (vm && vm.$callHook('onBackPress') === true) {
canBack = false
}
if (!canBack) {
return reject('onBackPress')
}
getApp().$router.go(-delta!)
return resolve()
},
NavigateBackProtocol,
NavigateBackOptions
)
......@@ -8,7 +8,8 @@ import { navigate } from './utils'
export const navigateTo = defineAsyncApi<typeof uni.navigateTo>(
API_NAVIGATE_TO,
({ url }) => navigate(API_NAVIGATE_TO, url),
({ url }, { resolve, reject }) =>
navigate(API_NAVIGATE_TO, url).then(resolve).catch(reject),
NavigateToProtocol,
NavigateToOptions
)
......@@ -8,7 +8,8 @@ import { navigate } from './utils'
export const reLaunch = defineAsyncApi<typeof uni.reLaunch>(
API_RE_LAUNCH,
({ url }) => navigate(API_RE_LAUNCH, url),
({ url }, { resolve, reject }) =>
navigate(API_RE_LAUNCH, url).then(resolve).catch(reject),
ReLaunchProtocol,
ReLaunchOptions
)
......@@ -8,7 +8,8 @@ import { navigate } from './utils'
export const redirectTo = defineAsyncApi<typeof uni.redirectTo>(
API_REDIRECT_TO,
({ url }) => navigate(API_REDIRECT_TO, url),
({ url }, { resolve, reject }) =>
navigate(API_REDIRECT_TO, url).then(resolve).catch(reject),
RedirectToProtocol,
RedirectToOptions
)
......@@ -8,7 +8,8 @@ import { navigate } from './utils'
export const switchTab = defineAsyncApi<typeof uni.switchTab>(
API_SWITCH_TAB,
({ url }) => navigate(API_SWITCH_TAB, url),
({ url }, { resolve, reject }) =>
navigate(API_SWITCH_TAB, url).then(resolve).catch(reject),
SwitchTabProtocol,
SwitchTabOptions
)
import { isArray, hasOwn, isObject, capitalize, toRawType, makeMap, isPlainObject, isFunction, extend, isPromise, isString } from '@vue/shared';
import { isArray, hasOwn, isObject, capitalize, toRawType, makeMap, isPlainObject, isPromise, isFunction, isString } from '@vue/shared';
function validateProtocolFail(name, msg) {
const errMsg = `${name}:fail ${msg}`;
......@@ -140,115 +140,6 @@ function isBoolean(...args) {
return args.some((elem) => elem.toLowerCase() === 'boolean');
}
function tryCatch(fn) {
return function () {
try {
return fn.apply(fn, arguments);
}
catch (e) {
// TODO
console.error(e);
}
};
}
let invokeCallbackId = 1;
const invokeCallbacks = {};
function addInvokeCallback(id, name, callback, keepAlive = false) {
invokeCallbacks[id] = {
name,
keepAlive,
callback,
};
return id;
}
// onNativeEventReceive((event,data)=>{}) 需要两个参数,目前写死最多两个参数
function invokeCallback(id, res, extras) {
if (typeof id === 'number') {
const opts = invokeCallbacks[id];
if (opts) {
if (!opts.keepAlive) {
delete invokeCallbacks[id];
}
return opts.callback(res, extras);
}
}
return res;
}
function findInvokeCallbackByName(name) {
for (const key in invokeCallbacks) {
if (invokeCallbacks[key].name === name) {
return true;
}
}
return false;
}
function removeKeepAliveApiCallback(name, callback) {
for (const key in invokeCallbacks) {
const item = invokeCallbacks[key];
if (item.callback === callback && item.name === name) {
delete invokeCallbacks[key];
}
}
}
function offKeepAliveApiCallback(name) {
UniServiceJSBridge.off('api.' + name);
}
function onKeepAliveApiCallback(name) {
UniServiceJSBridge.on('api.' + name, (res) => {
for (const key in invokeCallbacks) {
const opts = invokeCallbacks[key];
if (opts.name === name) {
opts.callback(res);
}
}
});
}
function createKeepAliveApiCallback(name, callback) {
return addInvokeCallback(invokeCallbackId++, name, callback, true);
}
function getApiCallbacks(args) {
const apiCallbacks = {};
for (const name in args) {
const fn = args[name];
if (isFunction(fn)) {
apiCallbacks[name] = tryCatch(fn);
delete args[name];
}
}
return apiCallbacks;
}
function normalizeErrMsg(errMsg, name) {
if (!errMsg || errMsg.indexOf(':fail') === -1) {
return name + ':ok';
}
return name + errMsg.substring(errMsg.indexOf(':fail'));
}
function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = {}) {
if (!isPlainObject(args)) {
args = {};
}
const { success, fail, complete } = getApiCallbacks(args);
const hasSuccess = isFunction(success);
const hasFail = isFunction(fail);
const hasComplete = isFunction(complete);
const callbackId = invokeCallbackId++;
addInvokeCallback(callbackId, name, (res) => {
res = res || {};
res.errMsg = normalizeErrMsg(res.errMsg, name);
isFunction(beforeAll) && beforeAll(res);
if (res.errMsg === name + ':ok') {
isFunction(beforeSuccess) && beforeSuccess(res);
hasSuccess && success(res);
}
else {
hasFail && fail(res);
}
hasComplete && complete(res);
});
return callbackId;
}
function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) {
return promise
......@@ -260,11 +151,6 @@ function handlePromise(promise) {
return promise;
}
const API_TYPE_ON = 0;
const API_TYPE_OFF = 1;
const API_TYPE_TASK = 2;
const API_TYPE_SYNC = 3;
const API_TYPE_ASYNC = 4;
function formatApiArgs(args, options) {
const params = args[0];
if (!options ||
......@@ -277,55 +163,9 @@ function formatApiArgs(args, options) {
});
return args;
}
function wrapperOnApi(name, fn) {
return (callback) => {
// 是否是首次调用on,如果是首次,需要初始化onMethod监听
const isFirstInvokeOnApi = !findInvokeCallbackByName(name);
createKeepAliveApiCallback(name, callback);
if (isFirstInvokeOnApi) {
onKeepAliveApiCallback(name);
fn();
}
};
}
function wrapperOffApi(name, fn) {
return (callback) => {
name = name.replace('off', 'on');
removeKeepAliveApiCallback(name, callback);
// 是否还存在监听,若已不存在,则移除onMethod监听
const hasInvokeOnApi = findInvokeCallbackByName(name);
if (!hasInvokeOnApi) {
offKeepAliveApiCallback(name);
fn();
}
};
}
function invokeSuccess(id, name, res) {
return invokeCallback(id, extend(res || {}, { errMsg: name + ':ok' }));
}
function invokeFail(id, name, err) {
return invokeCallback(id, { errMsg: name + ':fail' + (err ? ' ' + err : '') });
}
function wrapperTaskApi(name, fn, options) {
return (args) => {
const id = createAsyncApiCallback(name, args, options);
return fn(args, {
resolve: (res) => invokeSuccess(id, name, res),
reject: (err) => invokeFail(id, name, err),
});
};
}
function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args);
}
function wrapperAsyncApi(name, fn, options) {
return (args) => {
const id = createAsyncApiCallback(name, args, options);
fn(args)
.then((res) => invokeSuccess(id, name, res))
.catch((err) => invokeFail(id, name, err));
};
}
function wrapperApi(fn, name, protocol, options) {
return function (...args) {
if ((process.env.NODE_ENV !== 'production')) {
......@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) {
};
}
function defineSyncApi(name, fn, protocol, options) {
return defineApi(API_TYPE_SYNC, name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
}
function defineApi(type, name, fn, protocol, options) {
switch (type) {
case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol, options);
case API_TYPE_OFF:
return wrapperApi(wrapperOffApi(name, fn), name, protocol, options);
case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol, options);
case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol, options);
case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol, options);
}
return wrapperApi(wrapperSyncApi(fn), name, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
}
function getBaseSystemInfo() {
......
import { isArray, hasOwn, isObject, capitalize, toRawType, makeMap, isPlainObject, isFunction, extend, isPromise, isString } from '@vue/shared';
import { isArray, hasOwn, isObject, capitalize, toRawType, makeMap, isPlainObject, isPromise, isFunction, isString } from '@vue/shared';
function validateProtocolFail(name, msg) {
const errMsg = `${name}:fail ${msg}`;
......@@ -140,115 +140,6 @@ function isBoolean(...args) {
return args.some((elem) => elem.toLowerCase() === 'boolean');
}
function tryCatch(fn) {
return function () {
try {
return fn.apply(fn, arguments);
}
catch (e) {
// TODO
console.error(e);
}
};
}
let invokeCallbackId = 1;
const invokeCallbacks = {};
function addInvokeCallback(id, name, callback, keepAlive = false) {
invokeCallbacks[id] = {
name,
keepAlive,
callback,
};
return id;
}
// onNativeEventReceive((event,data)=>{}) 需要两个参数,目前写死最多两个参数
function invokeCallback(id, res, extras) {
if (typeof id === 'number') {
const opts = invokeCallbacks[id];
if (opts) {
if (!opts.keepAlive) {
delete invokeCallbacks[id];
}
return opts.callback(res, extras);
}
}
return res;
}
function findInvokeCallbackByName(name) {
for (const key in invokeCallbacks) {
if (invokeCallbacks[key].name === name) {
return true;
}
}
return false;
}
function removeKeepAliveApiCallback(name, callback) {
for (const key in invokeCallbacks) {
const item = invokeCallbacks[key];
if (item.callback === callback && item.name === name) {
delete invokeCallbacks[key];
}
}
}
function offKeepAliveApiCallback(name) {
UniServiceJSBridge.off('api.' + name);
}
function onKeepAliveApiCallback(name) {
UniServiceJSBridge.on('api.' + name, (res) => {
for (const key in invokeCallbacks) {
const opts = invokeCallbacks[key];
if (opts.name === name) {
opts.callback(res);
}
}
});
}
function createKeepAliveApiCallback(name, callback) {
return addInvokeCallback(invokeCallbackId++, name, callback, true);
}
function getApiCallbacks(args) {
const apiCallbacks = {};
for (const name in args) {
const fn = args[name];
if (isFunction(fn)) {
apiCallbacks[name] = tryCatch(fn);
delete args[name];
}
}
return apiCallbacks;
}
function normalizeErrMsg(errMsg, name) {
if (!errMsg || errMsg.indexOf(':fail') === -1) {
return name + ':ok';
}
return name + errMsg.substring(errMsg.indexOf(':fail'));
}
function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = {}) {
if (!isPlainObject(args)) {
args = {};
}
const { success, fail, complete } = getApiCallbacks(args);
const hasSuccess = isFunction(success);
const hasFail = isFunction(fail);
const hasComplete = isFunction(complete);
const callbackId = invokeCallbackId++;
addInvokeCallback(callbackId, name, (res) => {
res = res || {};
res.errMsg = normalizeErrMsg(res.errMsg, name);
isFunction(beforeAll) && beforeAll(res);
if (res.errMsg === name + ':ok') {
isFunction(beforeSuccess) && beforeSuccess(res);
hasSuccess && success(res);
}
else {
hasFail && fail(res);
}
hasComplete && complete(res);
});
return callbackId;
}
function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) {
return promise
......@@ -260,11 +151,6 @@ function handlePromise(promise) {
return promise;
}
const API_TYPE_ON = 0;
const API_TYPE_OFF = 1;
const API_TYPE_TASK = 2;
const API_TYPE_SYNC = 3;
const API_TYPE_ASYNC = 4;
function formatApiArgs(args, options) {
const params = args[0];
if (!options ||
......@@ -277,55 +163,9 @@ function formatApiArgs(args, options) {
});
return args;
}
function wrapperOnApi(name, fn) {
return (callback) => {
// 是否是首次调用on,如果是首次,需要初始化onMethod监听
const isFirstInvokeOnApi = !findInvokeCallbackByName(name);
createKeepAliveApiCallback(name, callback);
if (isFirstInvokeOnApi) {
onKeepAliveApiCallback(name);
fn();
}
};
}
function wrapperOffApi(name, fn) {
return (callback) => {
name = name.replace('off', 'on');
removeKeepAliveApiCallback(name, callback);
// 是否还存在监听,若已不存在,则移除onMethod监听
const hasInvokeOnApi = findInvokeCallbackByName(name);
if (!hasInvokeOnApi) {
offKeepAliveApiCallback(name);
fn();
}
};
}
function invokeSuccess(id, name, res) {
return invokeCallback(id, extend(res || {}, { errMsg: name + ':ok' }));
}
function invokeFail(id, name, err) {
return invokeCallback(id, { errMsg: name + ':fail' + (err ? ' ' + err : '') });
}
function wrapperTaskApi(name, fn, options) {
return (args) => {
const id = createAsyncApiCallback(name, args, options);
return fn(args, {
resolve: (res) => invokeSuccess(id, name, res),
reject: (err) => invokeFail(id, name, err),
});
};
}
function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args);
}
function wrapperAsyncApi(name, fn, options) {
return (args) => {
const id = createAsyncApiCallback(name, args, options);
fn(args)
.then((res) => invokeSuccess(id, name, res))
.catch((err) => invokeFail(id, name, err));
};
}
function wrapperApi(fn, name, protocol, options) {
return function (...args) {
if ((process.env.NODE_ENV !== 'production')) {
......@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) {
};
}
function defineSyncApi(name, fn, protocol, options) {
return defineApi(API_TYPE_SYNC, name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
}
function defineApi(type, name, fn, protocol, options) {
switch (type) {
case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol, options);
case API_TYPE_OFF:
return wrapperApi(wrapperOffApi(name, fn), name, protocol, options);
case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol, options);
case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol, options);
case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol, options);
}
return wrapperApi(wrapperSyncApi(fn), name, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
}
function getBaseSystemInfo() {
......
import { isArray, hasOwn, isObject, capitalize, toRawType, makeMap, isPlainObject, isFunction, extend, isPromise, isString } from '@vue/shared';
import { isArray, hasOwn, isObject, capitalize, toRawType, makeMap, isPlainObject, isPromise, isFunction, isString } from '@vue/shared';
function validateProtocolFail(name, msg) {
const errMsg = `${name}:fail ${msg}`;
......@@ -140,115 +140,6 @@ function isBoolean(...args) {
return args.some((elem) => elem.toLowerCase() === 'boolean');
}
function tryCatch(fn) {
return function () {
try {
return fn.apply(fn, arguments);
}
catch (e) {
// TODO
console.error(e);
}
};
}
let invokeCallbackId = 1;
const invokeCallbacks = {};
function addInvokeCallback(id, name, callback, keepAlive = false) {
invokeCallbacks[id] = {
name,
keepAlive,
callback,
};
return id;
}
// onNativeEventReceive((event,data)=>{}) 需要两个参数,目前写死最多两个参数
function invokeCallback(id, res, extras) {
if (typeof id === 'number') {
const opts = invokeCallbacks[id];
if (opts) {
if (!opts.keepAlive) {
delete invokeCallbacks[id];
}
return opts.callback(res, extras);
}
}
return res;
}
function findInvokeCallbackByName(name) {
for (const key in invokeCallbacks) {
if (invokeCallbacks[key].name === name) {
return true;
}
}
return false;
}
function removeKeepAliveApiCallback(name, callback) {
for (const key in invokeCallbacks) {
const item = invokeCallbacks[key];
if (item.callback === callback && item.name === name) {
delete invokeCallbacks[key];
}
}
}
function offKeepAliveApiCallback(name) {
UniServiceJSBridge.off('api.' + name);
}
function onKeepAliveApiCallback(name) {
UniServiceJSBridge.on('api.' + name, (res) => {
for (const key in invokeCallbacks) {
const opts = invokeCallbacks[key];
if (opts.name === name) {
opts.callback(res);
}
}
});
}
function createKeepAliveApiCallback(name, callback) {
return addInvokeCallback(invokeCallbackId++, name, callback, true);
}
function getApiCallbacks(args) {
const apiCallbacks = {};
for (const name in args) {
const fn = args[name];
if (isFunction(fn)) {
apiCallbacks[name] = tryCatch(fn);
delete args[name];
}
}
return apiCallbacks;
}
function normalizeErrMsg(errMsg, name) {
if (!errMsg || errMsg.indexOf(':fail') === -1) {
return name + ':ok';
}
return name + errMsg.substring(errMsg.indexOf(':fail'));
}
function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = {}) {
if (!isPlainObject(args)) {
args = {};
}
const { success, fail, complete } = getApiCallbacks(args);
const hasSuccess = isFunction(success);
const hasFail = isFunction(fail);
const hasComplete = isFunction(complete);
const callbackId = invokeCallbackId++;
addInvokeCallback(callbackId, name, (res) => {
res = res || {};
res.errMsg = normalizeErrMsg(res.errMsg, name);
isFunction(beforeAll) && beforeAll(res);
if (res.errMsg === name + ':ok') {
isFunction(beforeSuccess) && beforeSuccess(res);
hasSuccess && success(res);
}
else {
hasFail && fail(res);
}
hasComplete && complete(res);
});
return callbackId;
}
function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) {
return promise
......@@ -260,11 +151,6 @@ function handlePromise(promise) {
return promise;
}
const API_TYPE_ON = 0;
const API_TYPE_OFF = 1;
const API_TYPE_TASK = 2;
const API_TYPE_SYNC = 3;
const API_TYPE_ASYNC = 4;
function formatApiArgs(args, options) {
const params = args[0];
if (!options ||
......@@ -277,55 +163,9 @@ function formatApiArgs(args, options) {
});
return args;
}
function wrapperOnApi(name, fn) {
return (callback) => {
// 是否是首次调用on,如果是首次,需要初始化onMethod监听
const isFirstInvokeOnApi = !findInvokeCallbackByName(name);
createKeepAliveApiCallback(name, callback);
if (isFirstInvokeOnApi) {
onKeepAliveApiCallback(name);
fn();
}
};
}
function wrapperOffApi(name, fn) {
return (callback) => {
name = name.replace('off', 'on');
removeKeepAliveApiCallback(name, callback);
// 是否还存在监听,若已不存在,则移除onMethod监听
const hasInvokeOnApi = findInvokeCallbackByName(name);
if (!hasInvokeOnApi) {
offKeepAliveApiCallback(name);
fn();
}
};
}
function invokeSuccess(id, name, res) {
return invokeCallback(id, extend(res || {}, { errMsg: name + ':ok' }));
}
function invokeFail(id, name, err) {
return invokeCallback(id, { errMsg: name + ':fail' + (err ? ' ' + err : '') });
}
function wrapperTaskApi(name, fn, options) {
return (args) => {
const id = createAsyncApiCallback(name, args, options);
return fn(args, {
resolve: (res) => invokeSuccess(id, name, res),
reject: (err) => invokeFail(id, name, err),
});
};
}
function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args);
}
function wrapperAsyncApi(name, fn, options) {
return (args) => {
const id = createAsyncApiCallback(name, args, options);
fn(args)
.then((res) => invokeSuccess(id, name, res))
.catch((err) => invokeFail(id, name, err));
};
}
function wrapperApi(fn, name, protocol, options) {
return function (...args) {
if ((process.env.NODE_ENV !== 'production')) {
......@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) {
};
}
function defineSyncApi(name, fn, protocol, options) {
return defineApi(API_TYPE_SYNC, name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
}
function defineApi(type, name, fn, protocol, options) {
switch (type) {
case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol, options);
case API_TYPE_OFF:
return wrapperApi(wrapperOffApi(name, fn), name, protocol, options);
case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol, options);
case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol, options);
case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol, options);
}
return wrapperApi(wrapperSyncApi(fn), name, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
}
function getBaseSystemInfo() {
......
import { isArray, hasOwn, isObject, capitalize, toRawType, makeMap, isPlainObject, isFunction, extend, isPromise, isString } from '@vue/shared';
import { isArray, hasOwn, isObject, capitalize, toRawType, makeMap, isPlainObject, isPromise, isFunction, isString } from '@vue/shared';
function validateProtocolFail(name, msg) {
const errMsg = `${name}:fail ${msg}`;
......@@ -140,115 +140,6 @@ function isBoolean(...args) {
return args.some((elem) => elem.toLowerCase() === 'boolean');
}
function tryCatch(fn) {
return function () {
try {
return fn.apply(fn, arguments);
}
catch (e) {
// TODO
console.error(e);
}
};
}
let invokeCallbackId = 1;
const invokeCallbacks = {};
function addInvokeCallback(id, name, callback, keepAlive = false) {
invokeCallbacks[id] = {
name,
keepAlive,
callback,
};
return id;
}
// onNativeEventReceive((event,data)=>{}) 需要两个参数,目前写死最多两个参数
function invokeCallback(id, res, extras) {
if (typeof id === 'number') {
const opts = invokeCallbacks[id];
if (opts) {
if (!opts.keepAlive) {
delete invokeCallbacks[id];
}
return opts.callback(res, extras);
}
}
return res;
}
function findInvokeCallbackByName(name) {
for (const key in invokeCallbacks) {
if (invokeCallbacks[key].name === name) {
return true;
}
}
return false;
}
function removeKeepAliveApiCallback(name, callback) {
for (const key in invokeCallbacks) {
const item = invokeCallbacks[key];
if (item.callback === callback && item.name === name) {
delete invokeCallbacks[key];
}
}
}
function offKeepAliveApiCallback(name) {
UniServiceJSBridge.off('api.' + name);
}
function onKeepAliveApiCallback(name) {
UniServiceJSBridge.on('api.' + name, (res) => {
for (const key in invokeCallbacks) {
const opts = invokeCallbacks[key];
if (opts.name === name) {
opts.callback(res);
}
}
});
}
function createKeepAliveApiCallback(name, callback) {
return addInvokeCallback(invokeCallbackId++, name, callback, true);
}
function getApiCallbacks(args) {
const apiCallbacks = {};
for (const name in args) {
const fn = args[name];
if (isFunction(fn)) {
apiCallbacks[name] = tryCatch(fn);
delete args[name];
}
}
return apiCallbacks;
}
function normalizeErrMsg(errMsg, name) {
if (!errMsg || errMsg.indexOf(':fail') === -1) {
return name + ':ok';
}
return name + errMsg.substring(errMsg.indexOf(':fail'));
}
function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = {}) {
if (!isPlainObject(args)) {
args = {};
}
const { success, fail, complete } = getApiCallbacks(args);
const hasSuccess = isFunction(success);
const hasFail = isFunction(fail);
const hasComplete = isFunction(complete);
const callbackId = invokeCallbackId++;
addInvokeCallback(callbackId, name, (res) => {
res = res || {};
res.errMsg = normalizeErrMsg(res.errMsg, name);
isFunction(beforeAll) && beforeAll(res);
if (res.errMsg === name + ':ok') {
isFunction(beforeSuccess) && beforeSuccess(res);
hasSuccess && success(res);
}
else {
hasFail && fail(res);
}
hasComplete && complete(res);
});
return callbackId;
}
function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) {
return promise
......@@ -260,11 +151,6 @@ function handlePromise(promise) {
return promise;
}
const API_TYPE_ON = 0;
const API_TYPE_OFF = 1;
const API_TYPE_TASK = 2;
const API_TYPE_SYNC = 3;
const API_TYPE_ASYNC = 4;
function formatApiArgs(args, options) {
const params = args[0];
if (!options ||
......@@ -277,55 +163,9 @@ function formatApiArgs(args, options) {
});
return args;
}
function wrapperOnApi(name, fn) {
return (callback) => {
// 是否是首次调用on,如果是首次,需要初始化onMethod监听
const isFirstInvokeOnApi = !findInvokeCallbackByName(name);
createKeepAliveApiCallback(name, callback);
if (isFirstInvokeOnApi) {
onKeepAliveApiCallback(name);
fn();
}
};
}
function wrapperOffApi(name, fn) {
return (callback) => {
name = name.replace('off', 'on');
removeKeepAliveApiCallback(name, callback);
// 是否还存在监听,若已不存在,则移除onMethod监听
const hasInvokeOnApi = findInvokeCallbackByName(name);
if (!hasInvokeOnApi) {
offKeepAliveApiCallback(name);
fn();
}
};
}
function invokeSuccess(id, name, res) {
return invokeCallback(id, extend(res || {}, { errMsg: name + ':ok' }));
}
function invokeFail(id, name, err) {
return invokeCallback(id, { errMsg: name + ':fail' + (err ? ' ' + err : '') });
}
function wrapperTaskApi(name, fn, options) {
return (args) => {
const id = createAsyncApiCallback(name, args, options);
return fn(args, {
resolve: (res) => invokeSuccess(id, name, res),
reject: (err) => invokeFail(id, name, err),
});
};
}
function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args);
}
function wrapperAsyncApi(name, fn, options) {
return (args) => {
const id = createAsyncApiCallback(name, args, options);
fn(args)
.then((res) => invokeSuccess(id, name, res))
.catch((err) => invokeFail(id, name, err));
};
}
function wrapperApi(fn, name, protocol, options) {
return function (...args) {
if ((process.env.NODE_ENV !== 'production')) {
......@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) {
};
}
function defineSyncApi(name, fn, protocol, options) {
return defineApi(API_TYPE_SYNC, name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
}
function defineApi(type, name, fn, protocol, options) {
switch (type) {
case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol, options);
case API_TYPE_OFF:
return wrapperApi(wrapperOffApi(name, fn), name, protocol, options);
case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol, options);
case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol, options);
case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol, options);
}
return wrapperApi(wrapperSyncApi(fn), name, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
}
function getBaseSystemInfo() {
......
import { isArray, hasOwn, isObject, capitalize, toRawType, makeMap, isPlainObject, isFunction, extend, isPromise, isString } from '@vue/shared';
import { isArray, hasOwn, isObject, capitalize, toRawType, makeMap, isPlainObject, isPromise, isFunction, isString } from '@vue/shared';
function validateProtocolFail(name, msg) {
const errMsg = `${name}:fail ${msg}`;
......@@ -140,115 +140,6 @@ function isBoolean(...args) {
return args.some((elem) => elem.toLowerCase() === 'boolean');
}
function tryCatch(fn) {
return function () {
try {
return fn.apply(fn, arguments);
}
catch (e) {
// TODO
console.error(e);
}
};
}
let invokeCallbackId = 1;
const invokeCallbacks = {};
function addInvokeCallback(id, name, callback, keepAlive = false) {
invokeCallbacks[id] = {
name,
keepAlive,
callback,
};
return id;
}
// onNativeEventReceive((event,data)=>{}) 需要两个参数,目前写死最多两个参数
function invokeCallback(id, res, extras) {
if (typeof id === 'number') {
const opts = invokeCallbacks[id];
if (opts) {
if (!opts.keepAlive) {
delete invokeCallbacks[id];
}
return opts.callback(res, extras);
}
}
return res;
}
function findInvokeCallbackByName(name) {
for (const key in invokeCallbacks) {
if (invokeCallbacks[key].name === name) {
return true;
}
}
return false;
}
function removeKeepAliveApiCallback(name, callback) {
for (const key in invokeCallbacks) {
const item = invokeCallbacks[key];
if (item.callback === callback && item.name === name) {
delete invokeCallbacks[key];
}
}
}
function offKeepAliveApiCallback(name) {
UniServiceJSBridge.off('api.' + name);
}
function onKeepAliveApiCallback(name) {
UniServiceJSBridge.on('api.' + name, (res) => {
for (const key in invokeCallbacks) {
const opts = invokeCallbacks[key];
if (opts.name === name) {
opts.callback(res);
}
}
});
}
function createKeepAliveApiCallback(name, callback) {
return addInvokeCallback(invokeCallbackId++, name, callback, true);
}
function getApiCallbacks(args) {
const apiCallbacks = {};
for (const name in args) {
const fn = args[name];
if (isFunction(fn)) {
apiCallbacks[name] = tryCatch(fn);
delete args[name];
}
}
return apiCallbacks;
}
function normalizeErrMsg(errMsg, name) {
if (!errMsg || errMsg.indexOf(':fail') === -1) {
return name + ':ok';
}
return name + errMsg.substring(errMsg.indexOf(':fail'));
}
function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = {}) {
if (!isPlainObject(args)) {
args = {};
}
const { success, fail, complete } = getApiCallbacks(args);
const hasSuccess = isFunction(success);
const hasFail = isFunction(fail);
const hasComplete = isFunction(complete);
const callbackId = invokeCallbackId++;
addInvokeCallback(callbackId, name, (res) => {
res = res || {};
res.errMsg = normalizeErrMsg(res.errMsg, name);
isFunction(beforeAll) && beforeAll(res);
if (res.errMsg === name + ':ok') {
isFunction(beforeSuccess) && beforeSuccess(res);
hasSuccess && success(res);
}
else {
hasFail && fail(res);
}
hasComplete && complete(res);
});
return callbackId;
}
function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) {
return promise
......@@ -260,11 +151,6 @@ function handlePromise(promise) {
return promise;
}
const API_TYPE_ON = 0;
const API_TYPE_OFF = 1;
const API_TYPE_TASK = 2;
const API_TYPE_SYNC = 3;
const API_TYPE_ASYNC = 4;
function formatApiArgs(args, options) {
const params = args[0];
if (!options ||
......@@ -277,55 +163,9 @@ function formatApiArgs(args, options) {
});
return args;
}
function wrapperOnApi(name, fn) {
return (callback) => {
// 是否是首次调用on,如果是首次,需要初始化onMethod监听
const isFirstInvokeOnApi = !findInvokeCallbackByName(name);
createKeepAliveApiCallback(name, callback);
if (isFirstInvokeOnApi) {
onKeepAliveApiCallback(name);
fn();
}
};
}
function wrapperOffApi(name, fn) {
return (callback) => {
name = name.replace('off', 'on');
removeKeepAliveApiCallback(name, callback);
// 是否还存在监听,若已不存在,则移除onMethod监听
const hasInvokeOnApi = findInvokeCallbackByName(name);
if (!hasInvokeOnApi) {
offKeepAliveApiCallback(name);
fn();
}
};
}
function invokeSuccess(id, name, res) {
return invokeCallback(id, extend(res || {}, { errMsg: name + ':ok' }));
}
function invokeFail(id, name, err) {
return invokeCallback(id, { errMsg: name + ':fail' + (err ? ' ' + err : '') });
}
function wrapperTaskApi(name, fn, options) {
return (args) => {
const id = createAsyncApiCallback(name, args, options);
return fn(args, {
resolve: (res) => invokeSuccess(id, name, res),
reject: (err) => invokeFail(id, name, err),
});
};
}
function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args);
}
function wrapperAsyncApi(name, fn, options) {
return (args) => {
const id = createAsyncApiCallback(name, args, options);
fn(args)
.then((res) => invokeSuccess(id, name, res))
.catch((err) => invokeFail(id, name, err));
};
}
function wrapperApi(fn, name, protocol, options) {
return function (...args) {
if ((process.env.NODE_ENV !== 'production')) {
......@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) {
};
}
function defineSyncApi(name, fn, protocol, options) {
return defineApi(API_TYPE_SYNC, name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
}
function defineApi(type, name, fn, protocol, options) {
switch (type) {
case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol, options);
case API_TYPE_OFF:
return wrapperApi(wrapperOffApi(name, fn), name, protocol, options);
case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol, options);
case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol, options);
case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol, options);
}
return wrapperApi(wrapperSyncApi(fn), name, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
}
function getBaseSystemInfo() {
......
import { isArray, hasOwn, isObject, capitalize, toRawType, makeMap, isPlainObject, isFunction, extend, isPromise, isString } from '@vue/shared';
import { isArray, hasOwn, isObject, capitalize, toRawType, makeMap, isPlainObject, isPromise, isFunction, isString } from '@vue/shared';
function validateProtocolFail(name, msg) {
const errMsg = `${name}:fail ${msg}`;
......@@ -140,115 +140,6 @@ function isBoolean(...args) {
return args.some((elem) => elem.toLowerCase() === 'boolean');
}
function tryCatch(fn) {
return function () {
try {
return fn.apply(fn, arguments);
}
catch (e) {
// TODO
console.error(e);
}
};
}
let invokeCallbackId = 1;
const invokeCallbacks = {};
function addInvokeCallback(id, name, callback, keepAlive = false) {
invokeCallbacks[id] = {
name,
keepAlive,
callback,
};
return id;
}
// onNativeEventReceive((event,data)=>{}) 需要两个参数,目前写死最多两个参数
function invokeCallback(id, res, extras) {
if (typeof id === 'number') {
const opts = invokeCallbacks[id];
if (opts) {
if (!opts.keepAlive) {
delete invokeCallbacks[id];
}
return opts.callback(res, extras);
}
}
return res;
}
function findInvokeCallbackByName(name) {
for (const key in invokeCallbacks) {
if (invokeCallbacks[key].name === name) {
return true;
}
}
return false;
}
function removeKeepAliveApiCallback(name, callback) {
for (const key in invokeCallbacks) {
const item = invokeCallbacks[key];
if (item.callback === callback && item.name === name) {
delete invokeCallbacks[key];
}
}
}
function offKeepAliveApiCallback(name) {
UniServiceJSBridge.off('api.' + name);
}
function onKeepAliveApiCallback(name) {
UniServiceJSBridge.on('api.' + name, (res) => {
for (const key in invokeCallbacks) {
const opts = invokeCallbacks[key];
if (opts.name === name) {
opts.callback(res);
}
}
});
}
function createKeepAliveApiCallback(name, callback) {
return addInvokeCallback(invokeCallbackId++, name, callback, true);
}
function getApiCallbacks(args) {
const apiCallbacks = {};
for (const name in args) {
const fn = args[name];
if (isFunction(fn)) {
apiCallbacks[name] = tryCatch(fn);
delete args[name];
}
}
return apiCallbacks;
}
function normalizeErrMsg(errMsg, name) {
if (!errMsg || errMsg.indexOf(':fail') === -1) {
return name + ':ok';
}
return name + errMsg.substring(errMsg.indexOf(':fail'));
}
function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = {}) {
if (!isPlainObject(args)) {
args = {};
}
const { success, fail, complete } = getApiCallbacks(args);
const hasSuccess = isFunction(success);
const hasFail = isFunction(fail);
const hasComplete = isFunction(complete);
const callbackId = invokeCallbackId++;
addInvokeCallback(callbackId, name, (res) => {
res = res || {};
res.errMsg = normalizeErrMsg(res.errMsg, name);
isFunction(beforeAll) && beforeAll(res);
if (res.errMsg === name + ':ok') {
isFunction(beforeSuccess) && beforeSuccess(res);
hasSuccess && success(res);
}
else {
hasFail && fail(res);
}
hasComplete && complete(res);
});
return callbackId;
}
function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) {
return promise
......@@ -260,11 +151,6 @@ function handlePromise(promise) {
return promise;
}
const API_TYPE_ON = 0;
const API_TYPE_OFF = 1;
const API_TYPE_TASK = 2;
const API_TYPE_SYNC = 3;
const API_TYPE_ASYNC = 4;
function formatApiArgs(args, options) {
const params = args[0];
if (!options ||
......@@ -277,55 +163,9 @@ function formatApiArgs(args, options) {
});
return args;
}
function wrapperOnApi(name, fn) {
return (callback) => {
// 是否是首次调用on,如果是首次,需要初始化onMethod监听
const isFirstInvokeOnApi = !findInvokeCallbackByName(name);
createKeepAliveApiCallback(name, callback);
if (isFirstInvokeOnApi) {
onKeepAliveApiCallback(name);
fn();
}
};
}
function wrapperOffApi(name, fn) {
return (callback) => {
name = name.replace('off', 'on');
removeKeepAliveApiCallback(name, callback);
// 是否还存在监听,若已不存在,则移除onMethod监听
const hasInvokeOnApi = findInvokeCallbackByName(name);
if (!hasInvokeOnApi) {
offKeepAliveApiCallback(name);
fn();
}
};
}
function invokeSuccess(id, name, res) {
return invokeCallback(id, extend(res || {}, { errMsg: name + ':ok' }));
}
function invokeFail(id, name, err) {
return invokeCallback(id, { errMsg: name + ':fail' + (err ? ' ' + err : '') });
}
function wrapperTaskApi(name, fn, options) {
return (args) => {
const id = createAsyncApiCallback(name, args, options);
return fn(args, {
resolve: (res) => invokeSuccess(id, name, res),
reject: (err) => invokeFail(id, name, err),
});
};
}
function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args);
}
function wrapperAsyncApi(name, fn, options) {
return (args) => {
const id = createAsyncApiCallback(name, args, options);
fn(args)
.then((res) => invokeSuccess(id, name, res))
.catch((err) => invokeFail(id, name, err));
};
}
function wrapperApi(fn, name, protocol, options) {
return function (...args) {
if ((process.env.NODE_ENV !== 'production')) {
......@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) {
};
}
function defineSyncApi(name, fn, protocol, options) {
return defineApi(API_TYPE_SYNC, name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
}
function defineApi(type, name, fn, protocol, options) {
switch (type) {
case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol, options);
case API_TYPE_OFF:
return wrapperApi(wrapperOffApi(name, fn), name, protocol, options);
case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol, options);
case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol, options);
case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol, options);
}
return wrapperApi(wrapperSyncApi(fn), name, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
}
function getBaseSystemInfo() {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册