Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor of mp sdk, distinguish the origin mp sdk and wrapped sdk & f… #122

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions packages/page-spy-alipay/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import PageSpy, {
setMPSDK,
utilAPI,
Client,
SocketStoreBase,
platformAPI,
} from '@huolala-tech/page-spy-mp-base';
import { SpyClient } from '@huolala-tech/page-spy-types';

Expand All @@ -13,23 +13,23 @@ declare const my: any;
setMPSDK(my);

// alipay toxic storage api...
utilAPI.getStorage = (key: string) => {
platformAPI.getStorageSync = (key: string) => {
const res = my.getStorageSync({ key });
if (res.success) {
return res.data;
}
return undefined;
};

utilAPI.setStorage = (key: string, value: any) => {
platformAPI.setStorageSync = (key: string, value: any) => {
return my.setStorageSync({ key, data: value });
};

utilAPI.removeStorage = (key) => {
platformAPI.removeStorageSync = (key) => {
return my.removeStorageSync({ key });
};

utilAPI.showActionSheet = (params) => {
platformAPI.showActionSheet = (params) => {
return my.showActionSheet({
...params,
items: params.itemList,
Expand All @@ -41,6 +41,14 @@ utilAPI.showActionSheet = (params) => {
});
};

// TODO 个人小程序不支持该 api.. 先不管
platformAPI.setClipboardData = (params) => {
return my.setClipboard({
text: params.data,
...params,
});
};

const info = my.getSystemInfoSync();

PageSpy.client = new Client({
Expand Down
7 changes: 5 additions & 2 deletions packages/page-spy-mp-base/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import type { SpyMP } from '@huolala-tech/page-spy-types';
import { getRandomId } from '@huolala-tech/page-spy-base/dist/utils';
import type { Client } from '@huolala-tech/page-spy-base/dist/client';

import { getMPSDK, joinQuery, promisifyMPApi } from '../utils';
import { joinQuery, promisifyMPApi } from '../utils';
import { Config } from '../config';
import { getMPSDK } from '../helpers/mp-api';

interface TResponse<T> {
code: string;
Expand Down Expand Up @@ -56,6 +57,8 @@ export default class Request {
{
url: `${scheme[0]}${this.base}/api/v1/room/create?${query}`,
method: 'POST',
// uniapp building android native need this option.
sslVerify: enableSSL !== false,
data: JSON.stringify({
useSecret,
secret,
Expand All @@ -73,7 +76,7 @@ export default class Request {
},
(err) => {
/* c8 ignore next */
throw Error(`Request create room failed: ${err.message}`);
throw Error(`Request create room failed: ${err.message || err}`);
},
);
}
Expand Down
30 changes: 30 additions & 0 deletions packages/page-spy-mp-base/src/helpers/mp-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Wrap the mp api to smooth the platform differences, for internal usage only.
// This api can be modified by mp sdk implementor.
// This api should be passed through PageSpy instance to avoid esm multi-pack.

import { MPSDK } from '../types';

let mpSDK: MPSDK;

// the origin mp sdk, used for hacking
let originMPSDK: MPSDK;

// for API compatibility
// this api can be modified by mp sdk implementor, to smoothy the platform differences.
export const platformAPI = {} as MPSDK;
export const getMPSDK = () => {
if (!mpSDK) {
throw Error('the mp sdk is not set');
}
return mpSDK;
};

export const getOriginMPSDK = () => originMPSDK;

export const setMPSDK = (SDK: MPSDK) => {
originMPSDK = SDK;
mpSDK = {
...SDK,
...platformAPI,
};
};
5 changes: 3 additions & 2 deletions packages/page-spy-mp-base/src/helpers/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import {
SocketWrapper,
} from '@huolala-tech/page-spy-base/dist/socket-base';
import { ROOM_SESSION_KEY } from '@huolala-tech/page-spy-base/dist/constants';
import { getMPSDK, utilAPI } from '../utils';
import {
MPSocket,
SocketOnCloseHandler,
SocketOnErrorHandler,
SocketOnMessageHandler,
SocketOnOpenHandler,
} from '../types';
import { getMPSDK } from './mp-api';

export class MPSocketWrapper extends SocketWrapper {
public socketInstance: MPSocket | null = null;
Expand Down Expand Up @@ -94,7 +94,8 @@ export class MPSocketStore extends SocketStoreBase {
// this is an abstract method of parent class, cannot be static
/* eslint-disable-next-line */
onOffline() {
utilAPI.removeStorage(ROOM_SESSION_KEY);
const mp = getMPSDK();
mp.removeStorageSync(ROOM_SESSION_KEY);
}
}

Expand Down
32 changes: 16 additions & 16 deletions packages/page-spy-mp-base/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import Request from './api';
// import './index.less';
// eslint-disable-next-line import/order
import { Config } from './config';
import { getMPSDK, utilAPI } from './utils';
import { getMPSDK } from './helpers/mp-api';

type UpdateConfig = {
title?: string;
Expand Down Expand Up @@ -120,7 +120,8 @@ class PageSpy {
updateConfiguration() {
const { messageCapacity, useSecret } = this.config.get();
if (useSecret === true) {
const cache = utilAPI.getStorage(ROOM_SESSION_KEY);
const mp = getMPSDK();
const cache = mp.getStorageSync(ROOM_SESSION_KEY);
const secret = cache?.secret || getAuthSecret();
this.config.set('secret', secret);
psLog.log(`Room Secret: ${secret}`);
Expand All @@ -135,7 +136,7 @@ class PageSpy {
async init() {
const mp = getMPSDK();
const config = this.config.get();
const roomCache = utilAPI.getStorage(ROOM_SESSION_KEY);
const roomCache = mp.getStorageSync(ROOM_SESSION_KEY);
if (!roomCache || typeof roomCache !== 'object') {
await this.createNewConnection();
} else {
Expand Down Expand Up @@ -207,7 +208,7 @@ class PageSpy {
useSecret,
secret,
};
utilAPI.setStorage(ROOM_SESSION_KEY, roomCache);
getMPSDK().setStorageSync(ROOM_SESSION_KEY, roomCache);
}

triggerPlugins<T extends PageSpyPluginLifecycle>(
Expand Down Expand Up @@ -270,17 +271,15 @@ class PageSpy {
{
text: 'PageSpy 房间号:' + this.address.slice(0, 4),
action() {
if (mp.setClipboardData) {
mp.setClipboardData({
data: that.getDebugLink(),
success() {
mp.showToast({
title: '复制成功',
icon: 'success',
});
},
});
}
mp.setClipboardData({
data: that.getDebugLink(),
success() {
mp.showToast({
title: '复制成功',
icon: 'success',
});
},
});
},
},
];
Expand Down Expand Up @@ -309,7 +308,7 @@ class PageSpy {
}
});

utilAPI.showActionSheet({
mp.showActionSheet({
itemColor: '#b67cff',
itemList: options.map((o) => o.text),
success(res) {
Expand Down Expand Up @@ -386,3 +385,4 @@ export { SocketStoreBase, Client, psLog };
export * from './types';
export * from './utils';
export * from './helpers/socket';
export * from './helpers/mp-api';
4 changes: 2 additions & 2 deletions packages/page-spy-mp-base/src/plugins/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type {
OnInitParams,
} from '@huolala-tech/page-spy-types/index';
import socketStore from '../helpers/socket';
import { getMPSDK } from '../utils';
import { getMPSDK, getOriginMPSDK } from '../helpers/mp-api';

// TODO this plugin should test on multiple platforms
export default class ErrorPlugin implements PageSpyPlugin {
Expand All @@ -33,7 +33,7 @@ export default class ErrorPlugin implements PageSpyPlugin {
}

public onReset() {
const mp = getMPSDK();
const mp = getOriginMPSDK();
if (mp.canIUse('offError')) {
mp.offError(this.errorHandler);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import {
ReqReadyState,
toLowerKeys,
} from '@huolala-tech/page-spy-base/dist/network/common';
import { getMPSDK } from '../../../utils';
import MPNetworkProxyBase from './base';
import { MPNetworkAPI } from '../../../types';
import { getOriginMPSDK } from '../../../helpers/mp-api';

export default class MPWeixinRequestProxy extends MPNetworkProxyBase {
public request: MPNetworkAPI['request'] | null = null;
Expand All @@ -22,7 +22,7 @@ export default class MPWeixinRequestProxy extends MPNetworkProxyBase {

public reset() {
if (this.request) {
const mp = getMPSDK();
const mp = getOriginMPSDK();
Object.defineProperty(mp, 'request', {
value: this.request,
configurable: true,
Expand All @@ -34,7 +34,7 @@ export default class MPWeixinRequestProxy extends MPNetworkProxyBase {

public initProxyHandler() {
const that = this;
const mp = getMPSDK();
const mp = getOriginMPSDK();
const originRequest = mp.request;

if (!originRequest) {
Expand Down
15 changes: 7 additions & 8 deletions packages/page-spy-mp-base/src/plugins/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import type {
OnInitParams,
} from '@huolala-tech/page-spy-types';
import socketStore from '../helpers/socket';
import { getMPSDK, utilAPI } from '../utils';
import type { MPStorageAPI, KVList } from '../types';
import { getMPSDK, getOriginMPSDK } from '../helpers/mp-api';

const descriptor = {
configurable: true,
Expand Down Expand Up @@ -58,7 +58,7 @@ export default class StoragePlugin implements PageSpyPlugin {
}

public onReset() {
const mp = getMPSDK();
const mp = getOriginMPSDK();
Object.entries(StoragePlugin.originFunctions).forEach(([key, fn]) => {
Object.defineProperty(mp, key, {
value: fn,
Expand All @@ -76,7 +76,7 @@ export default class StoragePlugin implements PageSpyPlugin {
const data = info.keys.map((key) => {
return {
name: key,
value: mpDataStringify(utilAPI.getStorage(key)),
value: mpDataStringify(mp.getStorageSync(key)),
};
});

Expand All @@ -103,7 +103,7 @@ export default class StoragePlugin implements PageSpyPlugin {
/* c8 ignore stop */

public initStorageProxy() {
const mp = getMPSDK();
const mp = getOriginMPSDK();
const proxyFunctions = [
'setStorage',
'setStorageSync',
Expand Down Expand Up @@ -180,13 +180,12 @@ export default class StoragePlugin implements PageSpyPlugin {
},

removeStorageSync: {
// in alipay, the param is an object actually, but it works.
// TODO: really?
value(keyOrObj: string) {
value(keyOrObj: string | { key: string }) {
try {
const res =
StoragePlugin.originFunctions!.removeStorageSync(keyOrObj);
that.sendRemoveItem(keyOrObj);
const key = typeof keyOrObj === 'string' ? keyOrObj : keyOrObj.key;
that.sendRemoveItem(key);
return res;
/* c8 ignore next 4 */
} catch (e) {
Expand Down
2 changes: 1 addition & 1 deletion packages/page-spy-mp-base/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export type MPStorageAPI = {
} & AsyncCallback,
): void;

removeStorageSync(key: string): void;
removeStorageSync(key: string | { key: string }): void;

clearStorage(params: AsyncCallback): void;

Expand Down
30 changes: 0 additions & 30 deletions packages/page-spy-mp-base/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,6 @@ export const joinQuery = (args: Record<string, unknown>) => {
return arr.join('&');
};

let mpSDK: MPSDK;

export const getMPSDK = () => {
if (!mpSDK) {
throw Error('the mp sdk is not set');
}
return mpSDK;
};

export const setMPSDK = (SDK: MPSDK) => {
mpSDK = SDK;
};

// Some platform has no global object, we provide this function to manually create your own global object.
let customGlobal: Record<string, any> = {};
export const setCustomGlobal = (global: Record<string, any>) => {
Expand All @@ -60,20 +47,3 @@ export const getGlobal = () => {
}
return foundGlobal;
};

// wrap the mp api to smooth the platform differences, for internal usage only.
// this api can be modified by mp sdk implementor.
export const utilAPI = {
setStorage(key: string, data: any) {
return mpSDK?.setStorageSync(key, data);
},
getStorage(key: string) {
return mpSDK?.getStorageSync(key);
},
removeStorage(key: string) {
return mpSDK?.getStorageSync(key);
},
showActionSheet(params: Parameters<MPSDK['showActionSheet']>[0]) {
return mpSDK.showActionSheet(params);
},
};
3 changes: 1 addition & 2 deletions packages/page-spy-mp-base/tests/init.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import {
SpyMP,
} from '@huolala-tech/page-spy-types/index';
import { ROOM_SESSION_KEY } from 'page-spy-base/src';
import { initStorageMock } from './mock/storage';
import { mp } from './setup';
import { Config } from 'page-spy-mp-base/src/config';
import socket from 'page-spy-mp-base/src/helpers/socket';
Expand All @@ -31,7 +30,7 @@ let sdk: PageSpy | null;
PageSpy.client = new Client({}) as any;

beforeEach(() => {
initStorageMock();
mp.clearStorageSync();
});
afterEach(() => {
jest.restoreAllMocks();
Expand Down
Loading
Loading