perf-登录/request请求

This commit is contained in:
h_mo 2022-06-12 12:51:52 +08:00
parent b75f8cb143
commit a146e6bc18
17 changed files with 162 additions and 89 deletions

View File

@ -1,10 +1,13 @@
<script setup lang="ts">
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app';
import { useAuthStore } from '@/state/modules/auth';
onLaunch(() => {
console.log('App Launch');
});
onShow(() => {
const authStore = useAuthStore();
authStore.initToken();
console.log('App Show');
});
onHide(() => {

2
src/env.d.ts vendored
View File

@ -1,7 +1,5 @@
// / <reference types="vite/client" />
import { DEFAULT_PREFIX_KEY } from '@/settings/encryptionSetting';
declare module '*.vue' {
import { DefineComponent } from 'vue';
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types

View File

@ -16,38 +16,16 @@
import { ref, reactive } from 'vue';
import Test from '@/components/test/Test.vue';
const title = ref('Hello');
const url = import.meta.env.VITE_BASE_URL;
console.log('url', url);
type Data = {
token: string;
};
const jumLogin = () => {
console.log('/pages/login/index');
uni.navigateTo({
url: '/pages/login/index',
});
};
import { request } from '@/utils/http/index';
const form = reactive({
email: 'catch@admin.com',
password: 'catchadmin',
});
const loginType = ref('');
const submit = () => {
request
.post<Data>('/login', form)
.then((res) => {
loginType.value = '登录成功';
console.log(res.data.token);
})
.catch((err: any) => {
loginType.value = '登录失败';
console.log(err.message);
});
};
</script>
<style lang="scss">

View File

@ -9,7 +9,8 @@
>密码:
<input class="border border-gray-500" v-model="form.password" type="text" />
</label>
<button @tap="submit">login</button>
<button v-if="isLogin" @tap="loginOut">login out</button>
<button v-else @tap="submit">login</button>
{{ loginType }}
<view>{{ token }}---</view>
</view>
@ -18,29 +19,28 @@
<script setup lang="ts">
import { reactive, ref } from 'vue';
import { request } from '@/utils/http/index';
import { useUserStore } from '@/state/modules/user';
import { useAuthStore } from '@/state/modules/auth';
const form = reactive({
email: 'catch@admin.com',
password: 'catchadmin',
});
const loginType = ref('');
const token = ref<string>('');
const userStore = useUserStore();
const authStore = useAuthStore();
const token = ref<string | undefined>(authStore.getToken);
const isLogin = ref<boolean>(authStore.isLogin);
const submit = () => {
userStore.login(form);
// request
// .post('/login', form)
// .then((res: any) => {
// loginType.value = '';
// console.log(res);
// userStore.setToken(res.data.token);
// token.value = userStore.getToken;
// })
// .catch((err: any) => {
// loginType.value = '';
// console.log(err.message);
// });
authStore.login(form).then((res) => {
token.value = res.token;
isLogin.value = authStore.isLogin;
});
};
const loginOut = () => {
authStore.loginOut().then((res) => {
token.value = res.token;
isLogin.value = authStore.isLogin;
});
};
</script>

31
src/services/api/auth.ts Normal file
View File

@ -0,0 +1,31 @@
import { request } from '@/utils/http';
const LOGIN = '/login';
const LOGIN_OUT = '/logout';
const REFRESH_TOKEN = '/refresh/token';
/**
*
* @param params
*/
export function login(params: LoginParams) {
return request.post<API<LoginModel>>(LOGIN, params, {
custom: {
auth: false,
},
});
}
/**
*
*/
export function logout() {
return request.post<API>(LOGIN_OUT, {});
}
/**
* token
*/
export function refreshToken() {
return request.post<API<LoginModel>>(REFRESH_TOKEN, {});
}

View File

@ -1,7 +1 @@
import { request } from '@/utils/http';
const LOGIN = '/login';
export function login(params: LoginParams) {
return request.post<API<LoginModel>>(LOGIN, params);
}

View File

@ -1,4 +1,4 @@
declare interface API<T> {
declare interface API<T = any> {
code: number;
data?: T;
message: string;

0
src/services/model/userModel.d.ts vendored Normal file
View File

View File

@ -1,9 +1,11 @@
import { getPkgVersion, isDevMode } from '@/utils/env';
import { getEnvValue, getPkgVersion, isDevMode } from '@/utils/env';
// System default cache time, in seconds
export const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7;
const PREFIX =
import.meta.env.VITE_APP_CACHE_PREFIX || import.meta.env.VITE_APP_TITLE || 'UNI_APP_VUE3_TS';
getEnvValue<string>('VITE_APP_CACHE_PREFIX') ||
getEnvValue<string>('VITE_APP_TITLE') ||
'UNI_APP_VUE3_TS';
export const DEFAULT_PREFIX_KEY = `${PREFIX}${getPkgVersion()}`;
// aes encryption key

70
src/state/modules/auth.ts Normal file
View File

@ -0,0 +1,70 @@
import { defineStore } from 'pinia';
import { getCache, removeCache, setCache } from '@/utils/catch';
import { TOKEN_KEY } from '@/enums/cacheEnum';
import { login } from '@/services/api/auth';
import { logout, refreshToken } from '@/services/api/auth';
interface AuthState {
token?: string;
}
export const useAuthStore = defineStore({
id: 'auth',
state: (): AuthState => ({
token: undefined,
}),
getters: {
getToken: (state) => {
return state.token;
},
isLogin: (state): boolean => {
return !!state.token;
},
},
actions: {
initToken() {
this.token = getCache<string>(TOKEN_KEY) || undefined;
},
setToken(token: string | undefined) {
setCache(TOKEN_KEY, token);
this.token = token;
},
/**
* @description
*/
async login(params: LoginParams): Promise<LoginModel> {
try {
const { data } = await login(params);
this.setToken(data.token);
return Promise.resolve(data);
} catch (err: any) {
return Promise.reject(err);
}
},
/**
* @description
*/
async loginOut(): Promise<any> {
try {
const res = await logout();
removeCache(TOKEN_KEY);
this.setToken(undefined);
return Promise.resolve(res);
} catch (err: any) {
return Promise.reject(err);
}
},
/**
* @description token
*/
async refreshToken(): Promise<LoginModel> {
try {
const { data } = await refreshToken();
this.setToken(data.token);
return Promise.resolve(data);
} catch (err: any) {
return Promise.reject(err);
}
},
},
});

View File

@ -3,34 +3,11 @@ import { getCache, setCache } from '@/utils/catch';
import { TOKEN_KEY } from '@/enums/cacheEnum';
import { login } from '@/services/api/user';
interface UserState {
token?: string;
}
interface UserState {}
export const useUserStore = defineStore({
id: 'user',
state: (): UserState => ({
token: undefined,
}),
getters: {
getToken: (state) => state.token || getCache<string>(TOKEN_KEY),
},
actions: {
setToken(token: string) {
setCache(TOKEN_KEY, token);
this.token = token;
},
/**
* @description
*/
async login(params: LoginParams): Promise<LoginModel> {
try {
const { data } = await login(params);
this.setToken(data.token);
return Promise.resolve(data);
} catch (err: any) {
return Promise.reject(err);
}
},
},
state: (): UserState => ({}),
getters: {},
actions: {},
});

4
src/utils/auth.ts Normal file
View File

@ -0,0 +1,4 @@
import { getCache } from '@/utils/catch';
import { TOKEN_KEY } from '@/enums/cacheEnum';
export const TOKEN = () => getCache<string>(TOKEN_KEY) || undefined;

View File

@ -15,13 +15,23 @@ export const devMode = 'development';
*/
export const prodMode = 'production';
/**
* @description: Get environment mode
* @returns:
* @example:
*/
export function getEnvMode(): string {
return isDevMode() ? devMode : prodMode;
}
/**
* @description: Get environment variables
* @returns:
* @example:
*/
export function getEnv(): string {
return isDevMode() ? devMode : prodMode;
export function getEnvValue<T = any>(key: string): T {
// @ts-ignore
return import.meta.env[key];
}
/**
@ -30,7 +40,7 @@ export function getEnv(): string {
* @example:
*/
export function isDevMode(): boolean {
return import.meta.env.VITE_DEV;
return getEnvValue<boolean>('VITE_DEV');
}
/**
@ -39,5 +49,5 @@ export function isDevMode(): boolean {
* @example:
*/
export function isProdMode(): boolean {
return import.meta.env.VITE_PROD;
return getEnvValue<boolean>('VITE_PROD');
}

View File

@ -94,11 +94,11 @@ export default class Request {
* @prop {Object} [options.method = config.method] -
* @returns {Promise<unknown>}
*/
request<T>(config = {}) {
request<T>(config: Partial<HttpRequestConfig> = {}) {
return this.middleware<T>(config);
}
get<T>(url: string, options = {}) {
get<T>(url: string, options: Partial<HttpRequestConfig> = {}) {
return this.middleware<T>({
url,
method: 'GET',

View File

@ -5,8 +5,10 @@ import { assign } from 'lodash-es';
import { error } from '@/utils/log';
import { HttpSuccess } from '@/types/http';
import { Toast } from '@/utils/uniApi';
import { getEnvValue } from '@/utils/env';
import { useAuthStore } from '@/state/modules/auth';
const BASE_URL = import.meta.env.VITE_BASE_URL;
const BASE_URL = getEnvValue<string>('VITE_BASE_URL');
const HEADER = {
'Content-Type': 'application/json;charset=UTF-8;',
Accept: 'application/json, text/plain, */*',
@ -33,12 +35,14 @@ request.interceptors.request.use(
const { config } = options;
const token = TOKEN();
if (config.custom?.auth) {
if (!token) {
const authStore = useAuthStore();
if (!authStore.isLogin) {
Toast('请先登录');
// token不存在跳转到登录页
// return Promise.reject(options);
return Promise.reject(options);
}
config.header = assign(config.header, {
authorization: `Bearer ${token}`,
authorization: `Bearer ${authStore.getToken}`,
});
}
return options;

View File

@ -1,4 +1,6 @@
const projectName = import.meta.env.VITE_APP_TITLE;
import { getEnvValue } from '@/utils/env';
const projectName = getEnvValue<string>('VITE_APP_TITLE');
export function warn(message: string) {
console.warn(`[${projectName} warn]:${message}`);