chroe: Update server request.

mack-mac
mackt 8 months ago
parent 729a28b9ef
commit 81c352d376

@ -12,11 +12,13 @@ export interface ContributorCardType {
contributorRole: string; contributorRole: string;
} }
export default async function Download() { async function getContributorList() {
let contributorList: UserInfo[] = [];
const result = await apiThanks(); const result = await apiThanks();
if (result) contributorList = result; if (result.code === 200) return result.data;
}
export default async function About() {
const contributorList = await getContributorList();
return ( return (
<div className="w-full bg-[#F2F3F7]"> <div className="w-full bg-[#F2F3F7]">
@ -75,7 +77,7 @@ export default async function Download() {
</div> </div>
<div className="grid grid-cols-6 gap-6 mt-[26px]"> <div className="grid grid-cols-6 gap-6 mt-[26px]">
{contributorList.length && {!!contributorList?.length &&
contributorList.map((contributor) => <ContributorCard key={contributor.id} {...contributor} />)} contributorList.map((contributor) => <ContributorCard key={contributor.id} {...contributor} />)}
</div> </div>

@ -1,13 +1,14 @@
import { Category, JournalList, HotJournalList } from '@/components'; import { Category, JournalList, HotJournalList } from '@/components';
import { apiSearchCategory } from '@/services'; import { apiSearchCategory } from '@/services';
const getCategoryList = async () => {
const result = await apiSearchCategory();
return result.code === 200 ? result.data : [];
};
export default async function Journal({ params }: { params: { category?: string; page?: number } }) { export default async function Journal({ params }: { params: { category?: string; page?: number } }) {
const { category = 'all', page = 1 } = params; const { category = 'all', page = 1 } = params;
const result = await apiSearchCategory(); const categoryList = await getCategoryList();
let categoryList: Category[] = [];
if (result) {
categoryList = result;
}
const categoryInfo: Category | undefined = categoryList.find((item: Category) => item.nameEn === category); const categoryInfo: Category | undefined = categoryList.find((item: Category) => item.nameEn === category);
return ( return (

@ -2,13 +2,16 @@ import Link from 'next/link';
import { apiSearchCategory } from '@/services/server/journal'; import { apiSearchCategory } from '@/services/server/journal';
const Category = async ({ current = '' }: { current?: string }) => { const getCategoryList = async () => {
const result = await apiSearchCategory(); const result = await apiSearchCategory();
let categoryList: any = []; return result.code === 200 ? result.data : [];
if (result) categoryList = result; };
const Category = async ({ current = '' }: { current?: string }) => {
const categoryList = await getCategoryList();
categoryList.unshift({ categoryList.unshift({
id: 0, id: '0',
nameCh: '全部', nameCh: '全部',
nameEn: 'all', nameEn: 'all',
image: '', image: '',

@ -12,15 +12,23 @@ interface Props {
pageSize?: number; pageSize?: number;
} }
const getJournalList = async (params: {
categoryId?: string;
journalNoRange?: string;
pageNum?: number;
pageSize?: number;
}) => {
const res = await apiJournalList(params);
return res.code === 200 ? res.data : null;
};
const JournalList = async ({ categoryId, nameCh, journalNoRange, pageNum, pageSize }: Props) => { const JournalList = async ({ categoryId, nameCh, journalNoRange, pageNum, pageSize }: Props) => {
const res = await apiJournalList({ const journalList = await getJournalList({
categoryId, categoryId,
journalNoRange, journalNoRange,
pageNum, pageNum,
pageSize, pageSize,
}); });
let journalList;
if (res) journalList = res;
return ( return (
<div className="flex flex-col mt-[33px]"> <div className="flex flex-col mt-[33px]">
@ -35,7 +43,7 @@ const JournalList = async ({ categoryId, nameCh, journalNoRange, pageNum, pageSi
{/* 期刊 list */} {/* 期刊 list */}
<div className="flex flex-col gap-[60px] mt-[17px]"> <div className="flex flex-col gap-[60px] mt-[17px]">
{journalList?.rows.length && {journalList?.rows?.length &&
journalList.rows.map((item: JournalInfo) => <JournalItem key={item.id} {...item} />)} journalList.rows.map((item: JournalInfo) => <JournalItem key={item.id} {...item} />)}
</div> </div>
</div> </div>

@ -1,6 +1,6 @@
import { setCookie } from 'nookies'; import { setCookie } from 'nookies';
import clientHttp from '@/request/client'; import clientHttp from '@/utils/request/client';
import { request, verifyResponse } from '@/utils'; import { request, verifyResponse } from '@/utils';
/** /**

@ -1,6 +1,6 @@
// 期刊 // 期刊
import { request, verifyResponse } from '@/utils'; // import { request, verifyResponse } from '@/utils';
import serverHttp from '@/request/client'; import serverHttp from '@/utils/request/server';
/** /**
* @description 10 * @description 10
@ -9,54 +9,72 @@ import serverHttp from '@/request/client';
* @pageNum * @pageNum
* @pageSize * @pageSize
*/ */
export const apiJournalList = async ({ export const apiJournalList: (params: {
categoryId = '',
journalNoRange = '',
pageNum = 1,
pageSize = 10,
}: {
categoryId?: string; categoryId?: string;
journalNoRange?: string; journalNoRange?: string;
pageNum?: number; pageNum?: number;
pageSize?: number; pageSize?: number;
}) => Promise<FetchResponse<JournalList>> = async ({
categoryId = '',
journalNoRange = '',
pageNum = 1,
pageSize = 10,
}) => { }) => {
const result: FetchResponse<JournalList> = await serverHttp.get( const request = new Request(
`/luoo-music/journal/list?categoryId=${categoryId}&journalNoRange=${journalNoRange}&pageNum=${pageNum}&pageSize=${pageSize}`, `http://localhost?categoryId=${categoryId}&journalNoRange=${journalNoRange}&pageNum=${pageNum}&pageSize=${pageSize}`,
{
method: 'GET',
headers: {
requestUrl: '/luoo-music/journal/list',
},
},
); );
return result; const res = await serverHttp.get(request);
}; return res;
/**
* @description
*/
export const apiJournalFilter = async () => {
const result = await request('/luoo-music/journal/filter');
return result;
}; };
/** /**
* @description * @description
*/ */
export const apiSearchCategory = async () => { export const apiSearchCategory: () => Promise<FetchResponse<Category[]>> = async () => {
const result: FetchResponse<Category[]> = await request(`/luoo-music/search/category`); const request = new Request('http://localhost', {
method: 'GET',
return verifyResponse(result); headers: {
requestUrl: '/luoo-music/search/category',
},
});
const res = await serverHttp.get(request);
return res;
}; };
/** /**
* @description 6 * @description 6
* @id * @id
*/ */
export const apiJournalRecommend = async ({ id }: { id: string }) => { export const apiJournalRecommend: (params: { id: string }) => Promise<FetchResponse<JournalInfo[]>> = async ({
const result: FetchResponse<JournalInfo[]> = await serverHttp.get(`/luoo-music/journal/recommend/${id}`); id,
return result; }) => {
const request = new Request('http://localhost', {
method: 'GET',
headers: {
requestUrl: `/luoo-music/journal/recommend/${id}`,
},
});
const res = await serverHttp.get(request);
return res;
}; };
/** /**
* @description * @description
* @id * @id
*/ */
export const apiGetJournalById = async ({ id }: { id: string }) => { export const apiGetJournalById: (params: { id: string }) => Promise<FetchResponse<JournalInfo>> = async ({ id }) => {
const result: FetchResponse<JournalInfo> = await request(`/luoo-music/journal/journalNo/${id}`); const request = new Request('http://localhost', {
return verifyResponse(result); method: 'GET',
headers: {
requestUrl: `/luoo-music/journal/journalNo/${id}`,
},
});
const res = await serverHttp.get(request);
return res;
}; };

@ -1,4 +1,4 @@
import serverHttp from '@/request/client'; import serverHttp from '@/utils/request/client';
/** /**
* @description * @description

@ -1,18 +1,23 @@
import clientHttp from '@/request/client'; import serverHttp from '@/utils/request/server';
import { request, verifyResponse } from '@/utils';
/** /**
* @description * @description
*/ */
export const apiGetSupportedCountryCode = async () => { // export const apiGetSupportedCountryCode = async () => {
const res = await request('/luoo-user/user/supportedCountryCode'); // const res = await request('/luoo-user/user/supportedCountryCode');
return verifyResponse(res); // return verifyResponse(res);
}; // };
/** /**
* @description * @description
*/ */
export const apiThanks = async () => { export const apiThanks = async (): Promise<FetchResponse<UserInfo[]>> => {
const res: FetchResponse<UserInfo[]> = await clientHttp.get('/luoo-user/my/thanks'); const request = new Request('http://localhost', {
return verifyResponse(res); method: 'GET',
headers: {
requestUrl: '/luoo-user/my/thanks',
},
});
const res = await serverHttp.get(request);
return res;
}; };

@ -1,15 +1,3 @@
/**
* @description API URL
*/
export const getServerApiUrl = (originUrl: string): string => {
return `${process.env.NEXT_PUBLIC_HOST}${originUrl}`;
};
export const getClientApiUrl = (originUrl: string): string => {
return `queyueapi/${originUrl}`;
};
/** /**
* @description queryString * @description queryString
*/ */

@ -1,17 +0,0 @@
// server端
import { cookies } from 'next/headers';
export const nextFetchGet = async (api: string) => {
const nextCookies = cookies();
const token = nextCookies.get('token') || '';
const role = nextCookies.get('role');
const roleId = nextCookies.get('roleId');
const url = `${process.env.BASE_FETCH_URL}/queyueapi/be${api}`;
const res = await fetch(url, {
headers: token ? { Authorization: 'Bearer ' + token } : {},
});
if (!res.ok) {
throw new Error('Failed to fetch data');
}
return res.json();
};

@ -1,116 +0,0 @@
// client端请求
// import { getCookie } from './cookie';
// import { getApiUrl } from './helpers';
import { createFormBody } from './wrapper';
interface RequestOptions extends RequestInit {
responseType?: 'TEXT' | 'JSON' | 'BLOB' | 'ARRAYBUFFER' | 'text' | 'json' | 'blob' | 'arraybuffer';
body?: any;
}
// 发送数据请求
const request = async (url: string, config?: RequestOptions) => {
const method = config?.method || 'GET';
const finalUrl = method === 'POST' ? `/queyueapi${url}` : `${process.env.NEXT_PUBLIC_HOST}/${url}`;
const inital: RequestOptions = {
method: method,
body: null,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: '',
// 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxNzcyNjUzODM0MjYzNDY1OTg0Iiwic3ViIjoi6ZuA5LmQLWU5MnFQSHU2cSIsImlhdCI6MTcxMTU0MDgzOCwiYXZhdGFyIjoidXNlci9hdmF0YXIvZGVmYXVsdF8yMDI0MDIyN18yMzI5NDkuanBnIiwicm9sZXMiOiJ1c2VyIiwiZXhwIjoxNzEyMTQ1NjM4fQ.LqXi6ogm1jxK78-elx9vqNDQKXqzwQEoRRLpLj-PoGo',
},
credentials: 'include',
cache: 'no-cache',
mode: 'cors',
responseType: 'JSON',
};
const configs: RequestOptions = {
...inital,
...config,
};
if (config && config.headers)
configs.headers = {
...inital.headers,
Authorization:
'Bearer eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxNzcyNjUzODM0MjYzNDY1OTg0Iiwic3ViIjoi6ZuA5LmQLWU5MnFQSHU2cSIsImlhdCI6MTcxMTU0MDgzOCwiYXZhdGFyIjoidXNlci9hdmF0YXIvZGVmYXVsdF8yMDI0MDIyN18yMzI5NDkuanBnIiwicm9sZXMiOiJ1c2VyIiwiZXhwIjoxNzEyMTQ1NjM4fQ.LqXi6ogm1jxK78-elx9vqNDQKXqzwQEoRRLpLj-PoGo',
...config.headers,
};
// 基于fetch请求数据
const finalConfig: RequestInit = {
method: configs.method?.toUpperCase(),
credentials: configs.credentials,
mode: configs.mode,
cache: configs.cache,
headers: configs.headers,
body: method === 'POST' ? createFormBody(configs.body) : null,
};
return fetch(`${finalUrl}`, finalConfig)
.then((response: Response) => {
// 走到这边不一定是成功的:
// Fetch的特点的是只要服务器有返回结果不论状态码是多少它都认为是成功
const { status } = response;
if (status >= 200 && status < 400) {
// 真正成功获取数据
let result: any;
switch (configs.responseType && configs.responseType.toUpperCase()) {
case 'TEXT':
result = response.text();
break;
case 'JSON':
result = response.json();
break;
case 'BLOB':
result = response.blob();
break;
case 'ARRAYBUFFER':
result = response.arrayBuffer();
break;
default:
result = response.json();
}
return result;
}
// 失败的处理
return Promise.reject(response);
})
.catch((reason: any) => {
// @2:断网
if (typeof window !== 'undefined' && navigator && !navigator.onLine) {
console.log('Your network is break!');
}
// @1:状态码失败
if (reason && reason.status) {
switch (reason.status) {
case 400:
console.log('Please verify your info!');
break;
case 401:
console.log('Please Login!');
break;
case 403:
console.log('You have no access to this');
break;
case 500:
console.log("Oops, there's something wrong!");
break;
case 504:
console.log("Oops, there's something wrong!");
break;
default:
}
} else {
// @3:处理返回数据格式失败
console.log("Oops, there's something wrong!");
}
return Promise.reject(reason);
});
};
export default request;

@ -1,5 +1,11 @@
import { getAuthorization, getStringParams, handleResponse, hostMap, createFormBody } from '@/request/client/utils'; import {
import { IAuthType, IResponse } from '@/request/type'; getAuthorization,
getStringParams,
handleResponse,
hostMap,
createFormBody,
} from '@/utils/request/client/utils';
import { IAuthType, IResponse } from '@/utils/request/type';
export const post = async <T>(url: string, data: any, revalidate = 20): Promise<IResponse<T>> => { export const post = async <T>(url: string, data: any, revalidate = 20): Promise<IResponse<T>> => {
const token = await getAuthorization(); const token = await getAuthorization();

@ -3,8 +3,8 @@ import { parseCookies } from 'nookies';
import qs from 'qs'; import qs from 'qs';
import authOptions from '@/app/api/auth/[...nextauth]/options'; import authOptions from '@/app/api/auth/[...nextauth]/options';
import { IQueryParams, IResponse } from '@/request/type'; import { IQueryParams, IResponse } from '@/utils/request/type';
import { IAuthType, IResponse } from '@/request/type'; import { IAuthType, IResponse } from '@/utils/request/type';
// import jwtDecode from 'jwt-decode'; // import jwtDecode from 'jwt-decode';
const defaultHost = process.env.NEXT_PUBLIC_HOST; const defaultHost = process.env.NEXT_PUBLIC_HOST;

@ -1,7 +1,7 @@
import { NextResponse } from 'next/server'; import { NextResponse } from 'next/server';
import { formatBody } from '@/request/server/utils'; import { formatBody } from '@/utils/request/server/utils';
import { IAuthType } from '@/request/type'; import { IAuthType } from '@/utils/request/type';
const host = process.env.NEXT_PUBLIC_HOST; const host = process.env.NEXT_PUBLIC_HOST;
const get = async (request: Request) => { const get = async (request: Request) => {
try { try {
@ -9,7 +9,6 @@ const get = async (request: Request) => {
const token = request.headers.get('Authorization') as string; const token = request.headers.get('Authorization') as string;
const contentType = request.headers.get('Content-Type') as string; const contentType = request.headers.get('Content-Type') as string;
const requestUrl = request.headers.get('requestUrl') as string; const requestUrl = request.headers.get('requestUrl') as string;
const authType = request.headers.get('authType') as IAuthType;
const res = await fetch(`${host}${requestUrl}${search}`, { const res = await fetch(`${host}${requestUrl}${search}`, {
headers: { headers: {
'Content-Type': contentType, 'Content-Type': contentType,
@ -18,15 +17,13 @@ const get = async (request: Request) => {
method: 'GET', method: 'GET',
// cache: "force-cache", // cache: "force-cache",
}); });
// return NextResponse.json(res); return res.json();
return res;
} catch (error) { } catch (error) {
console.log('error: ', error);
return NextResponse.error(); return NextResponse.error();
} }
}; };
const post = async (request: RequesformatBodyt) => { const post = async (request: RequesformatBody) => {
try { try {
const { search } = new URL(request.url); const { search } = new URL(request.url);
const token = request.headers.get('Authorization') as string; const token = request.headers.get('Authorization') as string;

@ -1,18 +0,0 @@
type Response<T> = {
code: number;
message: string;
data: T;
};
const verify = <T>(obj: Response<T>): T | false => {
const { code, message, data } = obj;
if (code === 200) {
return data;
} else {
console.log(`错误code${code},${message}`);
return false;
}
};
export default verify;
Loading…
Cancel
Save