update: Add handling of client request token invalidation.

mack-mac
mackt 7 months ago
parent 36081edf9f
commit 4d50014d0d

@ -4,7 +4,6 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import Head from 'next/head';
import { useShallow } from 'zustand/react/shallow'; import { useShallow } from 'zustand/react/shallow';
import styles from './index.module.css'; import styles from './index.module.css';
@ -37,6 +36,7 @@ export default function Journal() {
// journal: apiGetSongCollect, // journal: apiGetSongCollect,
// }; // };
const result = await apiGetSongCollect({ userId: userInfo?.id, pageNum, pageSize }); const result = await apiGetSongCollect({ userId: userInfo?.id, pageNum, pageSize });
console.log(result.data);
if (result.code === 200) setList(result.data.rows); if (result.code === 200) setList(result.data.rows);
}; };

@ -18,6 +18,7 @@ export default function ButtonBar({
onShowInput, onShowInput,
onThumbup, onThumbup,
}: Props) { }: Props) {
const [displayThumbupCount, setDisplayThumbupCount] = useState<number>(0); // 页面展示的点赞数
const [showAll, setShowAll] = useState<boolean>(false); const [showAll, setShowAll] = useState<boolean>(false);
const [thumbup, setThumbup] = useState<boolean>(false); const [thumbup, setThumbup] = useState<boolean>(false);
@ -27,13 +28,16 @@ export default function ButtonBar({
}; };
const handleThumbup = async () => { const handleThumbup = async () => {
setThumbup(!thumbup);
const res = await onThumbup(); const res = await onThumbup();
if (res) setThumbup(!thumbup); if (res) {
setThumbup(!thumbup);
setDisplayThumbupCount(thumbup ? displayThumbupCount - 1 : displayThumbupCount + 1);
}
}; };
useEffect(() => { useEffect(() => {
setThumbup(haveThumbup); setThumbup(haveThumbup);
setDisplayThumbupCount(thumbupCount);
}, []); }, []);
return ( return (
@ -53,11 +57,11 @@ export default function ButtonBar({
)} )}
{/* 点赞 */} {/* 点赞 */}
<div className="w-[49px] h-[24px] group cursor-pointer" onClick={handleThumbup}> <div className="w-[49px] h-[24px] group cursor-pointer" onClick={handleThumbup}>
{thumbupCount > 0 && ( {displayThumbupCount > 0 && (
<div <div
className={`float-left mr-[2px] pt-[5px] ${thumbup ? 'text-theme' : 'text-[rgba(0, 0, 0, 0.7)]'} text-[12px] leading-[16.8px] group-hover:text-theme`} className={`float-left mr-[2px] pt-[5px] ${thumbup ? 'text-theme' : 'text-[rgba(0, 0, 0, 0.7)]'} text-[12px] leading-[16.8px] group-hover:text-theme`}
> >
{thumbupCount} {displayThumbupCount}
</div> </div>
)} )}
<div <div

@ -39,7 +39,7 @@ export default function UserCard({ onClose, className }: Props) {
}; };
const handleLogout = async () => { const handleLogout = async () => {
await userLogout; userLogout();
router.push('/'); router.push('/');
onClose(); onClose();
}; };

@ -21,7 +21,7 @@ export default function LoginForm() {
const [authCode, seAuthCode] = useState<string>('111111'); // 验证码 const [authCode, seAuthCode] = useState<string>('111111'); // 验证码
const [time, setTime] = useState<number>(0); // 倒计时 const [time, setTime] = useState<number>(0); // 倒计时
const [btnLoading, setBtnLoading] = useState<boolean>(false); const [btnLoading, setBtnLoading] = useState<boolean>(false);
const deviceId = 'aaaaaaaaaaaaa'; // 设备id 暂时写死 const deviceId = '1'; // 设备id 暂时写死
const activeSMS = useMemo(() => phone.length !== 11 || !!time, [phone, time]); // 是否激活发送短信按钮 const activeSMS = useMemo(() => phone.length !== 11 || !!time, [phone, time]); // 是否激活发送短信按钮
const activeLogin = useMemo(() => !(phone.length === 11 && authCode.length === 6), [phone, authCode]); // 是否激活发送短信按钮 const activeLogin = useMemo(() => !(phone.length === 11 && authCode.length === 6), [phone, authCode]); // 是否激活发送短信按钮
@ -40,7 +40,7 @@ export default function LoginForm() {
// 登录 // 登录
const handleLogin = async () => { const handleLogin = async () => {
const result = await userLogin({ mobile: phone, mobileCheckCode: authCode, deviceId: 'aaaaaaaaaaaaa' }); const result = await userLogin({ mobile: phone, mobileCheckCode: authCode, deviceId: '1' });
if (result) setShowLogin(false); if (result) setShowLogin(false);
}; };

@ -1,7 +1,7 @@
import clientHttp from '@/utils/request/client'; import clientHttp from '@/utils/request/client';
export const apiGetSongInfo = async (id: string) => { export const apiGetSongInfo = async (id: string) => {
const result: FetchResponse<SongInfo> = await clientHttp.get(`/luoo-music/song/${id}`); const result: FetchResponse<SongInfo> = await clientHttp.get(`/music/song/${id}`);
return result; return result;
}; };
@ -19,7 +19,7 @@ export const apiGetSongCollect = async ({
userId: string; userId: string;
}) => { }) => {
const result: FetchResponse<Paging<SongInfo>> = await clientHttp.get( const result: FetchResponse<Paging<SongInfo>> = await clientHttp.get(
`queyueapi/luoo-music/song/collect?userId=${userId}&pageNum=${pageNum}&pageSize=${pageSize}`, `queyueapi/music/song/collect?userId=${userId}&pageNum=${pageNum}&pageSize=${pageSize}`,
); );
return result; return result;
}; };

@ -8,14 +8,14 @@ interface CommentRequest {
export const apiGetCommentHot = async ({ journalId, page, size }: CommentRequest) => { export const apiGetCommentHot = async ({ journalId, page, size }: CommentRequest) => {
const result: FetchResponse<Paging<Comment>> = await clientHttp.get( const result: FetchResponse<Paging<Comment>> = await clientHttp.get(
`/queyueapi/luoo-comment/comment/hot/${journalId}/${page}/${size}`, `/queyueapi/comment/comment/hot/${journalId}/${page}/${size}`,
); );
return result; return result;
}; };
export const apiGetCommentNew = async ({ journalId, page, size }: CommentRequest) => { export const apiGetCommentNew = async ({ journalId, page, size }: CommentRequest) => {
const result: FetchResponse<Paging<Comment>> = await clientHttp.get( const result: FetchResponse<Paging<Comment>> = await clientHttp.get(
`/queyueapi/luoo-comment/comment/new/${journalId}/${page}/${size}`, `/queyueapi/comment/comment/new/${journalId}/${page}/${size}`,
); );
return result; return result;
}; };
@ -48,7 +48,7 @@ export const apiGetComment = async ({ type, journalId, page, size }: CommentRequ
*/ */
export const apiGetSubComment = async ({ parentId, page, size }: { parentId: string; page: number; size: number }) => { export const apiGetSubComment = async ({ parentId, page, size }: { parentId: string; page: number; size: number }) => {
const result: FetchResponse<Paging<Comment>> = await clientHttp.get( const result: FetchResponse<Paging<Comment>> = await clientHttp.get(
`/queyueapi/luoo-comment/comment/comment/${parentId}/${page}/${size}`, `/queyueapi/comment/comment/comment/${parentId}/${page}/${size}`,
); );
return result; return result;
}; };
@ -57,7 +57,7 @@ export const apiGetSubComment = async ({ parentId, page, size }: { parentId: str
* @description / * @description /
*/ */
export const apiCommentThumbup = async (commentId: string) => { export const apiCommentThumbup = async (commentId: string) => {
const result: FetchResponse<string> = await clientHttp.put(`/luoo-comment/comment/thumbup/${commentId}`); const result: FetchResponse<string> = await clientHttp.put(`/queyueapi/comment/comment/thumbup/${commentId}`);
return result; return result;
}; };
@ -68,6 +68,6 @@ export const apiCommentThumbup = async (commentId: string) => {
* @parentId id * @parentId id
*/ */
export const apiCommentSave = async (params: { content: string; journalId: string; parentId: string }) => { export const apiCommentSave = async (params: { content: string; journalId: string; parentId: string }) => {
const result: FetchResponse<string> = await clientHttp.post(`/luoo-comment/comment`, params); const result: FetchResponse<string> = await clientHttp.post(`/queyueapi/comment/comment`, params);
return result; return result;
}; };

@ -76,7 +76,7 @@ const useUserStore = create<UserState>()(
return await getUserInfo(); return await getUserInfo();
}, },
userLogout: async () => { userLogout: async () => {
await apiUserLogout(); apiUserLogout();
setUserInfo(initialUserInfo); setUserInfo(initialUserInfo);
destroyCookie(null, 'token'); destroyCookie(null, 'token');
}, },

@ -1,39 +0,0 @@
/**
* get client cookie
* @param {String} name cookie name
*/
export const getCookie = (name: string): string | undefined => {
const value = `; ${typeof window === 'undefined' ? '' : document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) {
const ppop = parts.pop();
if (ppop) {
return ppop.split(';').shift();
}
}
return '';
};
/**
* delete client cookie
* @param {String} name cookie name
*/
export const deleteCookie = (name: string) => {
const date = new Date();
date.setTime(date.getTime() - 10000);
document.cookie = name + '=; expire=' + date.toString();
};
/**
* set client cookie
* @param {String} name cookie name
* @param {String} value cookie value
*/
export const setCookie = (name: string, value: string) => {
const Days = 30;
const exp = new Date();
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
document.cookie = name + '=' + value + ';expires=' + exp.toString();
};

@ -0,0 +1,12 @@
import { destroyCookie } from 'nookies';
import { apiUserLogout } from '@/services';
const logout = () => {
apiUserLogout();
localStorage.clear();
destroyCookie(null, 'token');
window.location.href = '/';
};
export default logout;

@ -1,10 +1,14 @@
'use client';
import cloneDeep from 'lodash/cloneDeep'; import cloneDeep from 'lodash/cloneDeep';
import { parseCookies } from 'nookies'; import { parseCookies } from 'nookies';
import qs from 'qs'; import qs from 'qs';
import authOptions from '@/app/api/auth/[...nextauth]/options'; import logout from '@/utils/logout';
import { IQueryParams, IResponse } from '@/utils/request/type'; import { IQueryParams, IResponse } from '@/utils/request/type';
import { IAuthType, IResponse } from '@/utils/request/type';
import { apiAutoLogin } from '@/services';
// import jwtDecode from 'jwt-decode'; // import jwtDecode from 'jwt-decode';
const defaultHost = process.env.NEXT_PUBLIC_HOST; const defaultHost = process.env.NEXT_PUBLIC_HOST;
@ -46,7 +50,9 @@ export async function handleResponse<T>(response: globalThis.Response): Promise<
const contentType = response.headers.get('content-type'); const contentType = response.headers.get('content-type');
// 如果是json格式调用json解析 // 如果是json格式调用json解析
if (contentType && contentType.includes('application/json')) { if (contentType && contentType.includes('application/json')) {
return response.json(); const res = await response.json();
if (res.code === 401) await logout();
return res;
} }
return { return {
code: response.status, code: response.status,
@ -55,6 +61,13 @@ export async function handleResponse<T>(response: globalThis.Response): Promise<
} as IResponse<T>; } as IResponse<T>;
} }
export const checkState = async (response: globalThis.Response) => {
const res = await response.json();
if (res.code === 401) {
logout();
}
};
export const getStringParams = (params: IQueryParams) => { export const getStringParams = (params: IQueryParams) => {
// 深克隆一下以免传来的参数是redux等里面的数据修改会报错 // 深克隆一下以免传来的参数是redux等里面的数据修改会报错
const paramsCopy = cloneDeep(params); const paramsCopy = cloneDeep(params);
@ -66,6 +79,15 @@ export const getStringParams = (params: IQueryParams) => {
return qs.stringify(paramsCopy, { skipNulls: true }); return qs.stringify(paramsCopy, { skipNulls: true });
}; };
// token 续期
export const tokenRefresh = async () => {
const res = await apiAutoLogin({ deviceId: '1' });
if (res.code !== 200) {
await logout();
}
return res.data;
};
export const getAuthorization = async () => { export const getAuthorization = async () => {
// if (authType === 'noToken') return ''; // if (authType === 'noToken') return '';
const session: any = await parseCookies(); const session: any = await parseCookies();
@ -74,8 +96,8 @@ export const getAuthorization = async () => {
let authorization = ''; let authorization = '';
if (token && !isExpToken(expires)) { if (token && !isExpToken(expires)) {
authorization = token; authorization = token;
} else { } else if (token) {
return ''; return tokenRefresh();
// token 过期了重新登录请求然后给请求头设置好token // token 过期了重新登录请求然后给请求头设置好token
// 获取token的方法等也可以根据authType的不同进行自定义设置 // 获取token的方法等也可以根据authType的不同进行自定义设置
// const res = await getToken("账号密码等"); // const res = await getToken("账号密码等");

Loading…
Cancel
Save