feat: add MessageCenterHandler (#770)

Co-authored-by: Peng Xiao <pengxiao@freewheel.tv>
This commit is contained in:
Qi 2023-02-17 11:02:10 +08:00 committed by GitHub
parent f68b4934c6
commit cc1323f5cc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 78 additions and 46 deletions

View File

@ -0,0 +1,35 @@
import { toast } from '@affine/component';
import { getApis, MessageCenter } from '@affine/datacenter';
import { useRouter } from 'next/router';
import { useEffect } from 'react';
export function MessageCenterHandler({
children,
}: {
children?: React.ReactNode;
}) {
const router = useRouter();
useEffect(() => {
const instance = MessageCenter.getInstance();
if (instance) {
return instance.onMessage(async message => {
if (message.code === MessageCenter.messageCode.noPermission) {
// todo: translate message
// todo: more specific message for accessing different resources
// todo: error toast style
toast('You have no permission to access this workspace');
getApis().auth.clear();
// the status of the app right now is unknown, and it won't help if we let
// the app continue and let the user auth the app.
// that's why so we need to reload the page for now.
//
// fix: a better option is to keep loading the app, and prompt the user to login
// or perhaps displaying page 401?
router.reload();
}
});
}
}, [router]);
return <>{children}</>;
}

View File

@ -11,7 +11,7 @@ export const useMembers = () => {
const refreshMembers = useCallback(async () => {
if (!currentWorkspace || !dataCenter) return;
const members = await dataCenter.getMembers(currentWorkspace.id);
setMembers(members);
setMembers(members ?? []);
}, [dataCenter, currentWorkspace]);
useEffect(() => {

View File

@ -24,6 +24,7 @@ import { useTranslation } from '@affine/i18n';
import React from 'react';
import { GlobalAppProvider } from '@/store/app';
import { DataCenterPreloader } from '@/store/app/datacenter';
import { MessageCenterHandler } from '@/components/message-center-handler';
const ThemeProvider = dynamic(() => import('@/providers/ThemeProvider'), {
ssr: false,
@ -77,17 +78,19 @@ const App = ({ Component, pageProps }: AppPropsWithLayout) => {
<ConfirmProvider key="ConfirmProvider" />,
]}
>
{NoNeedAppStatePageList.includes(router.route) ? (
getLayout(<Component {...pageProps} />)
) : (
<Suspense fallback={<PageLoading />}>
<DataCenterPreloader>
<AppDefender>
{getLayout(<Component {...pageProps} />)}
</AppDefender>
</DataCenterPreloader>
</Suspense>
)}
<MessageCenterHandler>
{NoNeedAppStatePageList.includes(router.route) ? (
getLayout(<Component {...pageProps} />)
) : (
<Suspense fallback={<PageLoading />}>
<DataCenterPreloader>
<AppDefender>
{getLayout(<Component {...pageProps} />)}
</AppDefender>
</DataCenterPreloader>
</Suspense>
)}
</MessageCenterHandler>
</ProviderComposer>
</GlobalAppProvider>
</>

View File

@ -6,23 +6,25 @@ import type {
CreateWorkspaceInfoParams,
UpdateWorkspaceMetaParams,
} from './provider/base';
import { LocalProvider } from './provider/local/local';
import { LocalProvider } from './provider/local';
import { AffineProvider } from './provider';
import type { Message } from './types';
import assert from 'assert';
import { getLogger } from './logger';
import { createBlocksuiteWorkspace } from './utils/index';
import { createBlocksuiteWorkspace } from './utils';
import { MessageCenter } from './message';
import { WorkspaceUnit } from './workspace-unit';
/**
* @class DataCenter
* @classdesc Data center is made for managing different providers for business
*/
export class DataCenter {
private readonly _workspaceUnitCollection = new WorkspaceUnitCollection();
private readonly _logger = getLogger('dc');
private _workspaceInstances: Map<string, BlocksuiteWorkspace> = new Map();
private _messageCenter = MessageCenter.getInstance();
/**
* A mainProvider must exist as the only data trustworthy source.
*/
@ -304,7 +306,6 @@ export class DataCenter {
/**
* remove the new member to the workspace
* @param {number} permissionId permission id
*/
public async removeMember(workspaceId: string, permissionId: number) {
const workspaceInfo = this._workspaceUnitCollection.find(workspaceId);

View File

@ -32,5 +32,8 @@ export class MessageCenter extends Observable<string> {
public onMessage(callback: (message: Message) => void) {
this.on('message', callback);
return () => {
this.off('message', callback);
};
}
}

View File

@ -105,17 +105,21 @@ export class Auth {
type: 'Refresh',
token: refreshToken || this._refreshToken,
});
this._padding.finally(() => {
// clear on settled
this._padding = undefined;
});
this._refreshToken = refreshToken || this._refreshToken;
}
const res = await this._padding;
if (!refreshToken || refreshToken !== this._refreshToken) {
this.setLogin(res);
try {
const res = await this._padding;
if (res && (!refreshToken || refreshToken !== this._refreshToken)) {
this.setLogin(res);
}
return true;
} catch {
this._logger('Failed to refresh token');
} finally {
// clear on settled
this._padding = undefined;
}
return true;
return false;
}
get user() {

View File

@ -14,19 +14,15 @@ export const bareClient: KyInstance = ky.extend({
// todo: report timeout error
timeout: 60000,
hooks: {
// afterResponse: [
// async (_request, _options, response) => {
// if (response.status === 200) {
// const data = await response.json();
// if (data.error) {
// return new Response(data.error.message, {
// status: data.error.code,
// });
// }
// }
// return response;
// },
// ],
beforeError: [
error => {
const { response } = error;
if (response.status === 401) {
_sendMessage(MessageCenter.messageCode.noPermission);
}
return error;
},
],
},
});
@ -59,15 +55,5 @@ export const client: KyInstance = bareClient.extend({
request.headers.set('Authorization', auth.token);
},
],
beforeError: [
error => {
const { response } = error;
if (response.status === 401) {
_sendMessage(MessageCenter.messageCode.noPermission);
}
return error;
},
],
},
});