feat: improve code

This commit is contained in:
chenos 2022-02-24 16:52:35 +08:00
parent dc21859d55
commit f5b2600640
11 changed files with 71 additions and 16 deletions

1
.gitignore vendored
View File

@ -12,3 +12,4 @@ coverage
.umi .umi
/uploads /uploads
.env.test .env.test
docs-dist/

View File

@ -4,8 +4,4 @@ const apiClient = new APIClient({
baseURL: `http://localhost:3000/api/`, baseURL: `http://localhost:3000/api/`,
}); });
apiClient.setBearerToken();
// mock(apiClient);
export default apiClient; export default apiClient;

View File

@ -28,6 +28,8 @@ export class APIClient {
services: Record<string, Result<any, any>>; services: Record<string, Result<any, any>>;
tokenKey = 'nocobaseToken';
constructor(instance?: AxiosInstance | AxiosRequestConfig) { constructor(instance?: AxiosInstance | AxiosRequestConfig) {
this.services = observable({}); this.services = observable({});
if (typeof instance === 'function') { if (typeof instance === 'function') {
@ -35,11 +37,12 @@ export class APIClient {
} else { } else {
this.axios = axios.create(instance); this.axios = axios.create(instance);
} }
this.authMiddleware();
} }
setBearerToken(key = 'nocobaseToken') { authMiddleware() {
this.axios.interceptors.request.use((config) => { this.axios.interceptors.request.use((config) => {
const token = localStorage.getItem(key); const token = localStorage.getItem(this.tokenKey);
if (token) { if (token) {
config.headers['Authorization'] = `Bearer ${token}`; config.headers['Authorization'] = `Bearer ${token}`;
} }
@ -47,6 +50,10 @@ export class APIClient {
}); });
} }
setBearerToken(token: any) {
localStorage.setItem(this.tokenKey, token || '');
}
service(uid: string): Result<any, any> { service(uid: string): Result<any, any> {
return this.services[uid]; return this.services[uid];
} }

View File

@ -3,6 +3,7 @@ import React, { useRef, useState } from 'react';
import { useHistory, useRouteMatch } from 'react-router-dom'; import { useHistory, useRouteMatch } from 'react-router-dom';
import { import {
CurrentUser, CurrentUser,
CurrentUserProvider,
findByUid, findByUid,
findMenuItem, findMenuItem,
PluginManager, PluginManager,
@ -12,7 +13,7 @@ import {
useSystemSettings useSystemSettings
} from '../../../'; } from '../../../';
export function AdminLayout(props: any) { const InternalAdminLayout = (props: any) => {
const route = useRoute(); const route = useRoute();
const history = useHistory(); const history = useHistory();
const match = useRouteMatch<any>(); const match = useRouteMatch<any>();
@ -85,6 +86,14 @@ export function AdminLayout(props: any) {
</Layout> </Layout>
</Layout> </Layout>
); );
} };
export const AdminLayout = () => {
return (
<CurrentUserProvider>
<InternalAdminLayout />
</CurrentUserProvider>
);
};
export default AdminLayout; export default AdminLayout;

View File

@ -6,7 +6,7 @@ export function AuthLayout(props: any) {
style={{ style={{
maxWidth: 320, maxWidth: 320,
margin: '0 auto', margin: '0 auto',
// paddingTop: '20vh' paddingTop: '20vh',
}} }}
> >
<h1>NocoBase</h1> <h1>NocoBase</h1>

View File

@ -1,3 +1,10 @@
---
nav:
path: /client
group:
path: /schema-components
---
# Table # Table
表格有三个使用场景 表格有三个使用场景

View File

@ -2,12 +2,13 @@ import { Menu } from 'antd';
import React from 'react'; import React from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useHistory } from 'react-router-dom'; import { useHistory } from 'react-router-dom';
import { useDesignable } from '..'; import { useAPIClient, useDesignable } from '..';
import { ProfileAction } from './ProfileAction'; import { ProfileAction } from './ProfileAction';
export const CurrentUser = () => { export const CurrentUser = () => {
const history = useHistory(); const history = useHistory();
const { reset } = useDesignable(); const { reset } = useDesignable();
const api = useAPIClient();
const { i18n } = useTranslation(); const { i18n } = useTranslation();
return ( return (
<div style={{ display: 'inline-block' }}> <div style={{ display: 'inline-block' }}>
@ -27,6 +28,7 @@ export const CurrentUser = () => {
<Menu.Divider /> <Menu.Divider />
<Menu.Item <Menu.Item
onClick={() => { onClick={() => {
api.setBearerToken(null);
history.push('/signin'); history.push('/signin');
}} }}
> >

View File

@ -0,0 +1,19 @@
import { Spin } from 'antd';
import React, { createContext } from 'react';
import { Redirect } from 'react-router-dom';
import { useRequest } from '../api-client';
export const CurrentUserContext = createContext(null);
export const CurrentUserProvider = (props) => {
const result = useRequest({
url: 'users:check',
});
if (result.loading) {
return <Spin />;
}
if (result.error) {
return <Redirect to={'/signin'} />;
}
return <CurrentUserContext.Provider value={result}>{props.children}</CurrentUserContext.Provider>;
};

View File

@ -2,7 +2,7 @@ import { ISchema, useForm } from '@formily/react';
import { uid } from '@formily/shared'; import { uid } from '@formily/shared';
import React from 'react'; import React from 'react';
import { useHistory } from 'react-router-dom'; import { useHistory } from 'react-router-dom';
import { SchemaComponent, useCurrentDocumentTitle } from '..'; import { SchemaComponent, useAPIClient, useCurrentDocumentTitle } from '..';
const schema: ISchema = { const schema: ISchema = {
type: 'object', type: 'object',
@ -60,11 +60,17 @@ const schema: ISchema = {
const useSignin = () => { const useSignin = () => {
const history = useHistory(); const history = useHistory();
const form = useForm(); const form = useForm();
const api = useAPIClient();
return { return {
async run() { async run() {
await form.submit(); await form.submit();
console.log(form.values); const { data } = await api.resource('users').signin({
values: form.values,
});
if (data?.data?.token) {
api.setBearerToken(data?.data?.token);
history.push('/admin'); history.push('/admin');
}
}, },
}; };
}; };

View File

@ -1,8 +1,9 @@
import { ISchema, useForm } from '@formily/react'; import { ISchema, useForm } from '@formily/react';
import { uid } from '@formily/shared'; import { uid } from '@formily/shared';
import { message } from 'antd';
import React from 'react'; import React from 'react';
import { useHistory } from 'react-router-dom'; import { useHistory } from 'react-router-dom';
import { SchemaComponent, useCurrentDocumentTitle } from '..'; import { SchemaComponent, useAPIClient, useCurrentDocumentTitle } from '..';
const schema: ISchema = { const schema: ISchema = {
type: 'object', type: 'object',
@ -86,11 +87,17 @@ const schema: ISchema = {
const useSignup = () => { const useSignup = () => {
const history = useHistory(); const history = useHistory();
const form = useForm(); const form = useForm();
const api = useAPIClient();
return { return {
async run() { async run() {
await form.submit(); await form.submit();
console.log(form.values); await api.resource('users').signup({
// history.push('/signin'); values: form.values,
});
message.success('注册成功,即将跳转登录页');
setTimeout(() => {
history.push('/signin');
}, 2000);
}, },
}; };
}; };

View File

@ -1,4 +1,5 @@
export * from './CurrentUser'; export * from './CurrentUser';
export * from './CurrentUserProvider';
export * from './SigninPage'; export * from './SigninPage';
export * from './SignupPage'; export * from './SignupPage';