chroe: Update server request.

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

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

@ -1,13 +1,14 @@
import { Category, JournalList, HotJournalList } from '@/components';
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 } }) {
const { category = 'all', page = 1 } = params;
const result = await apiSearchCategory();
let categoryList: Category[] = [];
if (result) {
categoryList = result;
}
const categoryList = await getCategoryList();
const categoryInfo: Category | undefined = categoryList.find((item: Category) => item.nameEn === category);
return (

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

@ -12,15 +12,23 @@ interface Props {
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 res = await apiJournalList({
const journalList = await getJournalList({
categoryId,
journalNoRange,
pageNum,
pageSize,
});
let journalList;
if (res) journalList = res;
return (
<div className="flex flex-col mt-[33px]">
@ -35,7 +43,7 @@ const JournalList = async ({ categoryId, nameCh, journalNoRange, pageNum, pageSi
{/* 期刊 list */}
<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} />)}
</div>
</div>

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

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

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

@ -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 { IAuthType, IResponse } from '@/request/type';
import {
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>> => {
const token = await getAuthorization();

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

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