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

refactor: defineApi

上级 48dba672
...@@ -11,20 +11,6 @@ import { ...@@ -11,20 +11,6 @@ import {
removeKeepAliveApiCallback, removeKeepAliveApiCallback,
} from './callback' } from './callback'
import { promisify } from './promise' 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 { interface AsyncMethodOptionLike {
success?: (...args: any[]) => void success?: (...args: any[]) => void
} }
...@@ -131,17 +117,8 @@ function wrapperSyncApi(fn: Function) { ...@@ -131,17 +117,8 @@ function wrapperSyncApi(fn: Function) {
return (...args: any[]) => fn.apply(null, args) return (...args: any[]) => fn.apply(null, args)
} }
function wrapperAsyncApi( function wrapperAsyncApi(name: string, fn: Function, options?: ApiOptions) {
name: string, return wrapperTaskApi(name, fn, options)
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 wrapperApi( function wrapperApi(
...@@ -166,10 +143,9 @@ export function defineOnApi<T extends Function>( ...@@ -166,10 +143,9 @@ export function defineOnApi<T extends Function>(
fn: () => void, fn: () => void,
options?: ApiOptions options?: ApiOptions
) { ) {
return (defineApi( return (wrapperApi(
API_TYPE_ON, wrapperOnApi(name, fn),
name, name,
fn,
__DEV__ ? API_TYPE_ON_PROTOCOLS : undefined, __DEV__ ? API_TYPE_ON_PROTOCOLS : undefined,
options options
) as unknown) as T ) as unknown) as T
...@@ -180,10 +156,9 @@ export function defineOffApi<T extends Function>( ...@@ -180,10 +156,9 @@ export function defineOffApi<T extends Function>(
fn: () => void, fn: () => void,
options?: ApiOptions options?: ApiOptions
) { ) {
return (defineApi( return (wrapperApi(
API_TYPE_OFF, wrapperOffApi(name, fn),
name, name,
fn,
__DEV__ ? API_TYPE_ON_PROTOCOLS : undefined, __DEV__ ? API_TYPE_ON_PROTOCOLS : undefined,
options options
) as unknown) as T ) as unknown) as T
...@@ -194,7 +169,7 @@ export function defineTaskApi<T extends TaskApiLike, P = AsyncApiOptions<T>>( ...@@ -194,7 +169,7 @@ export function defineTaskApi<T extends TaskApiLike, P = AsyncApiOptions<T>>(
fn: ( fn: (
args: Omit<P, 'success' | 'fail' | 'complete'>, args: Omit<P, 'success' | 'fail' | 'complete'>,
res: { res: {
resolve: (res: AsyncApiRes<P>) => void resolve: (res?: AsyncApiRes<P>) => void
reject: (err?: string) => void reject: (err?: string) => void
} }
) => ReturnType<T>, ) => ReturnType<T>,
...@@ -202,7 +177,12 @@ export function defineTaskApi<T extends TaskApiLike, P = AsyncApiOptions<T>>( ...@@ -202,7 +177,12 @@ export function defineTaskApi<T extends TaskApiLike, P = AsyncApiOptions<T>>(
options?: ApiOptions options?: ApiOptions
) { ) {
return (promisify( 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 ) as unknown) as T
} }
...@@ -212,10 +192,9 @@ export function defineSyncApi<T extends Function>( ...@@ -212,10 +192,9 @@ export function defineSyncApi<T extends Function>(
protocol?: ApiProtocols, protocol?: ApiProtocols,
options?: ApiOptions options?: ApiOptions
) { ) {
return (defineApi( return (wrapperApi(
API_TYPE_SYNC, wrapperSyncApi(fn),
name, name,
fn,
__DEV__ ? protocol : undefined, __DEV__ ? protocol : undefined,
options options
) as unknown) as T ) as unknown) as T
...@@ -224,38 +203,21 @@ export function defineSyncApi<T extends Function>( ...@@ -224,38 +203,21 @@ export function defineSyncApi<T extends Function>(
export function defineAsyncApi<T extends AsyncApiLike, P = AsyncApiOptions<T>>( export function defineAsyncApi<T extends AsyncApiLike, P = AsyncApiOptions<T>>(
name: string, name: string,
fn: ( fn: (
args: Omit<P, 'success' | 'fail' | 'complete'> args: Omit<P, 'success' | 'fail' | 'complete'>,
) => Promise<AsyncApiRes<P> | void>, res: {
resolve: (res?: AsyncApiRes<P>) => void
reject: (err?: string) => void
}
) => void,
protocol?: ApiProtocols, protocol?: ApiProtocols,
options?: ApiOptions options?: ApiOptions
) { ) {
return promisify( 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> ) 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) { ...@@ -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) { function formatApiArgs(args, options) {
const params = args[0]; const params = args[0];
if (!options || !isPlainObject(options.formatArgs) && isPlainObject(params)) { if (!options || !isPlainObject(options.formatArgs) && isPlainObject(params)) {
...@@ -7835,10 +7830,7 @@ function wrapperSyncApi(fn) { ...@@ -7835,10 +7830,7 @@ function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args); return (...args) => fn.apply(null, args);
} }
function wrapperAsyncApi(name, fn, options) { function wrapperAsyncApi(name, fn, options) {
return (args) => { return wrapperTaskApi(name, fn, options);
const id2 = createAsyncApiCallback(name, args, options);
fn(args).then((res) => invokeSuccess(id2, name, res)).catch((err) => invokeFail(id2, name, err));
};
} }
function wrapperApi(fn, name, protocol, options) { function wrapperApi(fn, name, protocol, options) {
return function(...args) { return function(...args) {
...@@ -7852,33 +7844,19 @@ function wrapperApi(fn, name, protocol, options) { ...@@ -7852,33 +7844,19 @@ function wrapperApi(fn, name, protocol, options) {
}; };
} }
function defineOnApi(name, fn, 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) { 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) { 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) { 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) { function defineAsyncApi(name, fn, protocol, options) {
return promisify(defineApi(API_TYPE_ASYNC, name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options)); return promisify(wrapperApi(wrapperAsyncApi(name, fn, options), name, 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);
}
} }
const API_BASE64_TO_ARRAY_BUFFER = "base64ToArrayBuffer"; const API_BASE64_TO_ARRAY_BUFFER = "base64ToArrayBuffer";
const API_ARRAY_BUFFER_TO_BASE64 = "arrayBufferToBase64"; const API_ARRAY_BUFFER_TO_BASE64 = "arrayBufferToBase64";
...@@ -8419,9 +8397,9 @@ const canIUse = defineSyncApi(API_CAN_I_USE, (schema) => { ...@@ -8419,9 +8397,9 @@ const canIUse = defineSyncApi(API_CAN_I_USE, (schema) => {
} }
return true; return true;
}, CanIUseProtocol); }, CanIUseProtocol);
const makePhoneCall = defineAsyncApi(API_MAKE_PHONE_CALL, ({phoneNumber}) => { const makePhoneCall = defineAsyncApi(API_MAKE_PHONE_CALL, ({phoneNumber}, {resolve}) => {
window.location.href = `tel:${phoneNumber}`; window.location.href = `tel:${phoneNumber}`;
return Promise.resolve(); return resolve();
}, MakePhoneCallProtocol); }, MakePhoneCallProtocol);
const getSystemInfoSync = defineSyncApi("getSystemInfoSync", () => { const getSystemInfoSync = defineSyncApi("getSystemInfoSync", () => {
const pixelRatio2 = window.devicePixelRatio; const pixelRatio2 = window.devicePixelRatio;
...@@ -8523,8 +8501,8 @@ const getSystemInfoSync = defineSyncApi("getSystemInfoSync", () => { ...@@ -8523,8 +8501,8 @@ const getSystemInfoSync = defineSyncApi("getSystemInfoSync", () => {
} }
}; };
}); });
const getSystemInfo = defineAsyncApi("getSystemInfo", () => { const getSystemInfo = defineAsyncApi("getSystemInfo", (_args, {resolve}) => {
return Promise.resolve(getSystemInfoSync()); return resolve(getSystemInfoSync());
}); });
const API_ON_NETWORK_STATUS_CHANGE = "onNetworkStatusChange"; const API_ON_NETWORK_STATUS_CHANGE = "onNetworkStatusChange";
function networkListener() { function networkListener() {
...@@ -8556,7 +8534,7 @@ const offNetworkStatusChange = defineOffApi("offNetworkStatusChange", () => { ...@@ -8556,7 +8534,7 @@ const offNetworkStatusChange = defineOffApi("offNetworkStatusChange", () => {
window.removeEventListener("online", networkListener); window.removeEventListener("online", networkListener);
} }
}); });
const getNetworkType = defineAsyncApi("getNetworkType", () => { const getNetworkType = defineAsyncApi("getNetworkType", (_args, {resolve}) => {
const connection = getConnection(); const connection = getConnection();
let networkType = "unknown"; let networkType = "unknown";
if (connection) { if (connection) {
...@@ -8569,30 +8547,28 @@ const getNetworkType = defineAsyncApi("getNetworkType", () => { ...@@ -8569,30 +8547,28 @@ const getNetworkType = defineAsyncApi("getNetworkType", () => {
} else if (navigator.onLine === false) { } else if (navigator.onLine === false) {
networkType = "none"; 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); window.open(filePath);
return Promise.resolve(); return resolve();
}, OpenDocumentProtocol); }, OpenDocumentProtocol);
function _getServiceAddress() { function _getServiceAddress() {
return window.location.protocol + "//" + window.location.host; 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(); const img = new Image();
return new Promise((resolve, reject) => { img.onload = function() {
img.onload = function() { resolve({
resolve({ width: img.naturalWidth,
width: img.naturalWidth, height: img.naturalHeight,
height: img.naturalHeight, path: src.indexOf("/") === 0 ? _getServiceAddress() + src : src
path: src.indexOf("/") === 0 ? _getServiceAddress() + src : src });
}); };
}; img.onerror = function() {
img.onerror = function() { reject();
reject(); };
}; img.src = src;
img.src = src;
});
}, GetImageInfoProtocol, GetImageInfoOptions); }, GetImageInfoProtocol, GetImageInfoOptions);
const request = defineTaskApi(API_REQUEST, ({ const request = defineTaskApi(API_REQUEST, ({
url, url,
...@@ -8713,7 +8689,7 @@ function parseHeaders(headers) { ...@@ -8713,7 +8689,7 @@ function parseHeaders(headers) {
}); });
return headersObject; 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; let canBack = true;
const vm = getCurrentPageVm(); const vm = getCurrentPageVm();
if (vm && vm.$callHook("onBackPress") === true) { if (vm && vm.$callHook("onBackPress") === true) {
...@@ -8723,8 +8699,8 @@ const navigateBack = defineAsyncApi(API_NAVIGATE_BACK, ({delta}) => new Promise( ...@@ -8723,8 +8699,8 @@ const navigateBack = defineAsyncApi(API_NAVIGATE_BACK, ({delta}) => new Promise(
return reject("onBackPress"); return reject("onBackPress");
} }
getApp().$router.go(-delta); getApp().$router.go(-delta);
resolve(); return resolve();
}), NavigateBackProtocol, NavigateBackOptions); }, NavigateBackProtocol, NavigateBackOptions);
function navigate(type, url) { function navigate(type, url) {
const router = getApp().$router; const router = getApp().$router;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
...@@ -8740,10 +8716,10 @@ function navigate(type, url) { ...@@ -8740,10 +8716,10 @@ function navigate(type, url) {
}); });
}); });
} }
const navigateTo = defineAsyncApi(API_NAVIGATE_TO, ({url}) => navigate(API_NAVIGATE_TO, url), NavigateToProtocol, NavigateToOptions); 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}) => navigate(API_REDIRECT_TO, url), RedirectToProtocol, RedirectToOptions); 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}) => navigate(API_RE_LAUNCH, url), ReLaunchProtocol, ReLaunchOptions); 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}) => navigate(API_SWITCH_TAB, url), SwitchTabProtocol, SwitchTabOptions); 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({ var api = /* @__PURE__ */ Object.freeze({
__proto__: null, __proto__: null,
[Symbol.toStringTag]: "Module", [Symbol.toStringTag]: "Module",
......
...@@ -4,7 +4,7 @@ import { getSystemInfoSync } from './getSystemInfoSync' ...@@ -4,7 +4,7 @@ import { getSystemInfoSync } from './getSystemInfoSync'
export const getSystemInfo = defineAsyncApi<typeof uni.getSystemInfo>( export const getSystemInfo = defineAsyncApi<typeof uni.getSystemInfo>(
'getSystemInfo', 'getSystemInfo',
() => { (_args, { resolve }) => {
return Promise.resolve(getSystemInfoSync()) return resolve(getSystemInfoSync())
} }
) )
...@@ -6,9 +6,9 @@ import { ...@@ -6,9 +6,9 @@ import {
export const makePhoneCall = defineAsyncApi<typeof uni.makePhoneCall>( export const makePhoneCall = defineAsyncApi<typeof uni.makePhoneCall>(
API_MAKE_PHONE_CALL, API_MAKE_PHONE_CALL,
({ phoneNumber }) => { ({ phoneNumber }, { resolve }) => {
window.location.href = `tel:${phoneNumber}` window.location.href = `tel:${phoneNumber}`
return Promise.resolve() return resolve()
}, },
MakePhoneCallProtocol MakePhoneCallProtocol
) )
...@@ -51,7 +51,7 @@ export const offNetworkStatusChange = defineOffApi< ...@@ -51,7 +51,7 @@ export const offNetworkStatusChange = defineOffApi<
export const getNetworkType = defineAsyncApi<typeof uni.getNetworkType>( export const getNetworkType = defineAsyncApi<typeof uni.getNetworkType>(
'getNetworkType', 'getNetworkType',
() => { (_args, { resolve }) => {
const connection = getConnection() const connection = getConnection()
let networkType = 'unknown' let networkType = 'unknown'
if (connection) { if (connection) {
...@@ -64,6 +64,6 @@ export const getNetworkType = defineAsyncApi<typeof uni.getNetworkType>( ...@@ -64,6 +64,6 @@ export const getNetworkType = defineAsyncApi<typeof uni.getNetworkType>(
} else if (navigator.onLine === false) { } else if (navigator.onLine === false) {
networkType = 'none' networkType = 'none'
} }
return Promise.resolve({ networkType }) return resolve({ networkType })
} }
) )
...@@ -6,9 +6,9 @@ import { ...@@ -6,9 +6,9 @@ import {
export const openDocument = defineAsyncApi<typeof uni.openDocument>( export const openDocument = defineAsyncApi<typeof uni.openDocument>(
API_OPEN_DOCUMENT, API_OPEN_DOCUMENT,
({ filePath }) => { ({ filePath }, { resolve }) => {
window.open(filePath) window.open(filePath)
return Promise.resolve() return resolve()
}, },
OpenDocumentProtocol OpenDocumentProtocol
) )
...@@ -11,21 +11,19 @@ function _getServiceAddress() { ...@@ -11,21 +11,19 @@ function _getServiceAddress() {
export const getImageInfo = defineAsyncApi<typeof uni.getImageInfo>( export const getImageInfo = defineAsyncApi<typeof uni.getImageInfo>(
API_GET_IMAGE_INFO, API_GET_IMAGE_INFO,
({ src }) => { ({ src }, { resolve, reject }) => {
const img = new Image() const img = new Image()
return new Promise((resolve, reject) => { img.onload = function () {
img.onload = function () { resolve({
resolve({ width: img.naturalWidth,
width: img.naturalWidth, height: img.naturalHeight,
height: img.naturalHeight, path: src.indexOf('/') === 0 ? _getServiceAddress() + src : src,
path: src.indexOf('/') === 0 ? _getServiceAddress() + src : src, } as UniApp.GetImageInfoSuccessData) // orientation和type是可选的,但GetImageInfoSuccessData定义的不对,暂时强制转换
} as UniApp.GetImageInfoSuccessData) // orientation和type是可选的,但GetImageInfoSuccessData定义的不对,暂时强制转换 }
} img.onerror = function () {
img.onerror = function () { reject()
reject() }
} img.src = src
img.src = src
})
}, },
GetImageInfoProtocol, GetImageInfoProtocol,
GetImageInfoOptions GetImageInfoOptions
......
...@@ -8,19 +8,18 @@ import { ...@@ -8,19 +8,18 @@ import {
export const navigateBack = defineAsyncApi<typeof uni.navigateBack>( export const navigateBack = defineAsyncApi<typeof uni.navigateBack>(
API_NAVIGATE_BACK, API_NAVIGATE_BACK,
({ delta }) => ({ delta }, { resolve, reject }) => {
new Promise((resolve, reject) => { let canBack = true
let canBack = true const vm = getCurrentPageVm()
const vm = getCurrentPageVm() if (vm && vm.$callHook('onBackPress') === true) {
if (vm && vm.$callHook('onBackPress') === true) { canBack = false
canBack = false }
} if (!canBack) {
if (!canBack) { return reject('onBackPress')
return reject('onBackPress') }
} getApp().$router.go(-delta!)
getApp().$router.go(-delta!) return resolve()
resolve() },
}),
NavigateBackProtocol, NavigateBackProtocol,
NavigateBackOptions NavigateBackOptions
) )
...@@ -8,7 +8,8 @@ import { navigate } from './utils' ...@@ -8,7 +8,8 @@ import { navigate } from './utils'
export const navigateTo = defineAsyncApi<typeof uni.navigateTo>( export const navigateTo = defineAsyncApi<typeof uni.navigateTo>(
API_NAVIGATE_TO, API_NAVIGATE_TO,
({ url }) => navigate(API_NAVIGATE_TO, url), ({ url }, { resolve, reject }) =>
navigate(API_NAVIGATE_TO, url).then(resolve).catch(reject),
NavigateToProtocol, NavigateToProtocol,
NavigateToOptions NavigateToOptions
) )
...@@ -8,7 +8,8 @@ import { navigate } from './utils' ...@@ -8,7 +8,8 @@ import { navigate } from './utils'
export const reLaunch = defineAsyncApi<typeof uni.reLaunch>( export const reLaunch = defineAsyncApi<typeof uni.reLaunch>(
API_RE_LAUNCH, API_RE_LAUNCH,
({ url }) => navigate(API_RE_LAUNCH, url), ({ url }, { resolve, reject }) =>
navigate(API_RE_LAUNCH, url).then(resolve).catch(reject),
ReLaunchProtocol, ReLaunchProtocol,
ReLaunchOptions ReLaunchOptions
) )
...@@ -8,7 +8,8 @@ import { navigate } from './utils' ...@@ -8,7 +8,8 @@ import { navigate } from './utils'
export const redirectTo = defineAsyncApi<typeof uni.redirectTo>( export const redirectTo = defineAsyncApi<typeof uni.redirectTo>(
API_REDIRECT_TO, API_REDIRECT_TO,
({ url }) => navigate(API_REDIRECT_TO, url), ({ url }, { resolve, reject }) =>
navigate(API_REDIRECT_TO, url).then(resolve).catch(reject),
RedirectToProtocol, RedirectToProtocol,
RedirectToOptions RedirectToOptions
) )
...@@ -8,7 +8,8 @@ import { navigate } from './utils' ...@@ -8,7 +8,8 @@ import { navigate } from './utils'
export const switchTab = defineAsyncApi<typeof uni.switchTab>( export const switchTab = defineAsyncApi<typeof uni.switchTab>(
API_SWITCH_TAB, API_SWITCH_TAB,
({ url }) => navigate(API_SWITCH_TAB, url), ({ url }, { resolve, reject }) =>
navigate(API_SWITCH_TAB, url).then(resolve).catch(reject),
SwitchTabProtocol, SwitchTabProtocol,
SwitchTabOptions 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) { function validateProtocolFail(name, msg) {
const errMsg = `${name}:fail ${msg}`; const errMsg = `${name}:fail ${msg}`;
...@@ -140,115 +140,6 @@ function isBoolean(...args) { ...@@ -140,115 +140,6 @@ function isBoolean(...args) {
return args.some((elem) => elem.toLowerCase() === 'boolean'); 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) { function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) { if (__UNI_FEATURE_PROMISE__) {
return promise return promise
...@@ -260,11 +151,6 @@ function handlePromise(promise) { ...@@ -260,11 +151,6 @@ function handlePromise(promise) {
return 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) { function formatApiArgs(args, options) {
const params = args[0]; const params = args[0];
if (!options || if (!options ||
...@@ -277,55 +163,9 @@ function formatApiArgs(args, options) { ...@@ -277,55 +163,9 @@ function formatApiArgs(args, options) {
}); });
return args; 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) { function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args); 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) { function wrapperApi(fn, name, protocol, options) {
return function (...args) { return function (...args) {
if ((process.env.NODE_ENV !== 'production')) { if ((process.env.NODE_ENV !== 'production')) {
...@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) { ...@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) {
}; };
} }
function defineSyncApi(name, fn, protocol, options) { function defineSyncApi(name, fn, protocol, options) {
return defineApi(API_TYPE_SYNC, name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options); return wrapperApi(wrapperSyncApi(fn), name, (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);
}
} }
function getBaseSystemInfo() { 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) { function validateProtocolFail(name, msg) {
const errMsg = `${name}:fail ${msg}`; const errMsg = `${name}:fail ${msg}`;
...@@ -140,115 +140,6 @@ function isBoolean(...args) { ...@@ -140,115 +140,6 @@ function isBoolean(...args) {
return args.some((elem) => elem.toLowerCase() === 'boolean'); 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) { function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) { if (__UNI_FEATURE_PROMISE__) {
return promise return promise
...@@ -260,11 +151,6 @@ function handlePromise(promise) { ...@@ -260,11 +151,6 @@ function handlePromise(promise) {
return 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) { function formatApiArgs(args, options) {
const params = args[0]; const params = args[0];
if (!options || if (!options ||
...@@ -277,55 +163,9 @@ function formatApiArgs(args, options) { ...@@ -277,55 +163,9 @@ function formatApiArgs(args, options) {
}); });
return args; 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) { function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args); 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) { function wrapperApi(fn, name, protocol, options) {
return function (...args) { return function (...args) {
if ((process.env.NODE_ENV !== 'production')) { if ((process.env.NODE_ENV !== 'production')) {
...@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) { ...@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) {
}; };
} }
function defineSyncApi(name, fn, protocol, options) { function defineSyncApi(name, fn, protocol, options) {
return defineApi(API_TYPE_SYNC, name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options); return wrapperApi(wrapperSyncApi(fn), name, (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);
}
} }
function getBaseSystemInfo() { 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) { function validateProtocolFail(name, msg) {
const errMsg = `${name}:fail ${msg}`; const errMsg = `${name}:fail ${msg}`;
...@@ -140,115 +140,6 @@ function isBoolean(...args) { ...@@ -140,115 +140,6 @@ function isBoolean(...args) {
return args.some((elem) => elem.toLowerCase() === 'boolean'); 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) { function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) { if (__UNI_FEATURE_PROMISE__) {
return promise return promise
...@@ -260,11 +151,6 @@ function handlePromise(promise) { ...@@ -260,11 +151,6 @@ function handlePromise(promise) {
return 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) { function formatApiArgs(args, options) {
const params = args[0]; const params = args[0];
if (!options || if (!options ||
...@@ -277,55 +163,9 @@ function formatApiArgs(args, options) { ...@@ -277,55 +163,9 @@ function formatApiArgs(args, options) {
}); });
return args; 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) { function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args); 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) { function wrapperApi(fn, name, protocol, options) {
return function (...args) { return function (...args) {
if ((process.env.NODE_ENV !== 'production')) { if ((process.env.NODE_ENV !== 'production')) {
...@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) { ...@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) {
}; };
} }
function defineSyncApi(name, fn, protocol, options) { function defineSyncApi(name, fn, protocol, options) {
return defineApi(API_TYPE_SYNC, name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options); return wrapperApi(wrapperSyncApi(fn), name, (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);
}
} }
function getBaseSystemInfo() { 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) { function validateProtocolFail(name, msg) {
const errMsg = `${name}:fail ${msg}`; const errMsg = `${name}:fail ${msg}`;
...@@ -140,115 +140,6 @@ function isBoolean(...args) { ...@@ -140,115 +140,6 @@ function isBoolean(...args) {
return args.some((elem) => elem.toLowerCase() === 'boolean'); 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) { function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) { if (__UNI_FEATURE_PROMISE__) {
return promise return promise
...@@ -260,11 +151,6 @@ function handlePromise(promise) { ...@@ -260,11 +151,6 @@ function handlePromise(promise) {
return 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) { function formatApiArgs(args, options) {
const params = args[0]; const params = args[0];
if (!options || if (!options ||
...@@ -277,55 +163,9 @@ function formatApiArgs(args, options) { ...@@ -277,55 +163,9 @@ function formatApiArgs(args, options) {
}); });
return args; 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) { function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args); 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) { function wrapperApi(fn, name, protocol, options) {
return function (...args) { return function (...args) {
if ((process.env.NODE_ENV !== 'production')) { if ((process.env.NODE_ENV !== 'production')) {
...@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) { ...@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) {
}; };
} }
function defineSyncApi(name, fn, protocol, options) { function defineSyncApi(name, fn, protocol, options) {
return defineApi(API_TYPE_SYNC, name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options); return wrapperApi(wrapperSyncApi(fn), name, (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);
}
} }
function getBaseSystemInfo() { 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) { function validateProtocolFail(name, msg) {
const errMsg = `${name}:fail ${msg}`; const errMsg = `${name}:fail ${msg}`;
...@@ -140,115 +140,6 @@ function isBoolean(...args) { ...@@ -140,115 +140,6 @@ function isBoolean(...args) {
return args.some((elem) => elem.toLowerCase() === 'boolean'); 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) { function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) { if (__UNI_FEATURE_PROMISE__) {
return promise return promise
...@@ -260,11 +151,6 @@ function handlePromise(promise) { ...@@ -260,11 +151,6 @@ function handlePromise(promise) {
return 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) { function formatApiArgs(args, options) {
const params = args[0]; const params = args[0];
if (!options || if (!options ||
...@@ -277,55 +163,9 @@ function formatApiArgs(args, options) { ...@@ -277,55 +163,9 @@ function formatApiArgs(args, options) {
}); });
return args; 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) { function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args); 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) { function wrapperApi(fn, name, protocol, options) {
return function (...args) { return function (...args) {
if ((process.env.NODE_ENV !== 'production')) { if ((process.env.NODE_ENV !== 'production')) {
...@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) { ...@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) {
}; };
} }
function defineSyncApi(name, fn, protocol, options) { function defineSyncApi(name, fn, protocol, options) {
return defineApi(API_TYPE_SYNC, name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options); return wrapperApi(wrapperSyncApi(fn), name, (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);
}
} }
function getBaseSystemInfo() { 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) { function validateProtocolFail(name, msg) {
const errMsg = `${name}:fail ${msg}`; const errMsg = `${name}:fail ${msg}`;
...@@ -140,115 +140,6 @@ function isBoolean(...args) { ...@@ -140,115 +140,6 @@ function isBoolean(...args) {
return args.some((elem) => elem.toLowerCase() === 'boolean'); 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) { function handlePromise(promise) {
if (__UNI_FEATURE_PROMISE__) { if (__UNI_FEATURE_PROMISE__) {
return promise return promise
...@@ -260,11 +151,6 @@ function handlePromise(promise) { ...@@ -260,11 +151,6 @@ function handlePromise(promise) {
return 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) { function formatApiArgs(args, options) {
const params = args[0]; const params = args[0];
if (!options || if (!options ||
...@@ -277,55 +163,9 @@ function formatApiArgs(args, options) { ...@@ -277,55 +163,9 @@ function formatApiArgs(args, options) {
}); });
return args; 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) { function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args); 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) { function wrapperApi(fn, name, protocol, options) {
return function (...args) { return function (...args) {
if ((process.env.NODE_ENV !== 'production')) { if ((process.env.NODE_ENV !== 'production')) {
...@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) { ...@@ -338,21 +178,7 @@ function wrapperApi(fn, name, protocol, options) {
}; };
} }
function defineSyncApi(name, fn, protocol, options) { function defineSyncApi(name, fn, protocol, options) {
return defineApi(API_TYPE_SYNC, name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options); return wrapperApi(wrapperSyncApi(fn), name, (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);
}
} }
function getBaseSystemInfo() { function getBaseSystemInfo() {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册