Skip to content

Commit

Permalink
🐛 fix: resolve undefined when plugin is not in LobeChat
Browse files Browse the repository at this point in the history
  • Loading branch information
arvinxx committed Jan 10, 2024
1 parent c94b081 commit 53e36c1
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
9 changes: 9 additions & 0 deletions src/client/lobeChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,21 @@ class LobeChat {
resolve(undefined as any);
return;
}

const timer = setTimeout(() => {
resolve(undefined as any);
// eslint-disable-next-line @typescript-eslint/no-use-before-define
window.removeEventListener('message', receiverData);
}, 1000);

const receiverData = (e: MessageEvent) => {
if (e.data.type === PluginChannel.initStandalonePlugin) {
// TODO: drop e.data.props in v2
const payload: PluginRequestPayload = e.data.payload || e.data.props;
const func = payload.apiName;
const args = JSON.parse(payload.arguments || '{}');
clearTimeout(timer);

resolve({
arguments: args,
name: func,
Expand Down
21 changes: 20 additions & 1 deletion tests/client/lobeChat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ describe('lobeChat', () => {
});
});

describe('fetchPluginPayload', () => {
describe('getPluginPayload', () => {
it('should resolve undefined when window is undefined', async () => {
const originalWindow = global.window;
global.window = undefined as any;
Expand Down Expand Up @@ -172,6 +172,25 @@ describe('lobeChat', () => {
expect.any(Function),
);
});

it('should resolve undefined if message is not received within timeout', async () => {
vi.useFakeTimers();

const promise = lobeChat.getPluginPayload();

// Fast-forward until all timers have been executed
vi.runAllTimers();

const result = await promise;

expect(result).toBeUndefined();
expect(global.window.removeEventListener).toHaveBeenCalledWith(
'message',
expect.any(Function),
);

vi.useRealTimers();
});
});

describe('fetchPluginSettings', () => {
Expand Down

0 comments on commit 53e36c1

Please sign in to comment.