Skip to content

Commit def183f

Browse files
authored
Merge pull request #2 from martinwq997/main
test antd-message
2 parents f656322 + b7ce5d9 commit def183f

File tree

11 files changed

+1475
-2529
lines changed

11 files changed

+1475
-2529
lines changed

.env.example

Lines changed: 0 additions & 13 deletions
This file was deleted.

app/api/crates/route.ts

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
1-
// /home/rust/workspace/cratespro-frontend/app/api/programs/route.ts
21
import { NextRequest, NextResponse } from 'next/server';
3-
import pool from '../../lib/db';
42

53
export async function GET(req: NextRequest) {
64
try {
7-
const client = await pool.connect();
8-
const res = await client.query('SELECT name, description FROM programs');
9-
client.release();
5+
// 发送 HTTP 请求获取外部数据
6+
const externalApiUrl = 'http://210.28.134.203:6888/crates'; // 替换为你的外部 API URL
7+
const externalRes = await fetch(externalApiUrl);
108

11-
const programs = res.rows;
9+
if (!externalRes.ok) {
10+
throw new Error('Failed to fetch external data');
11+
}
1212

13-
return NextResponse.json(programs);
13+
const externalData = await externalRes.json();
14+
15+
return NextResponse.json(externalData);
1416
} catch (error) {
15-
console.error('Database query error:', error);
17+
console.error('Error:', error);
1618
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
1719
}
1820
}

app/api/submit/route.ts

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,25 @@
1-
import { NextRequest, NextResponse } from 'next/server';
2-
import pool from '../../lib/db'; // 导入数据库连接池
1+
import { NextResponse } from 'next/server';
32

4-
export async function POST(req: NextRequest) {
5-
try {
6-
const { content } = await req.json(); // 解析请求体中的 JSON 数据
3+
export async function POST(request: { json: () => any; }) {
4+
const apiUrl = process.env.API_URL; // 读取环境变量,获取后端服务的基础 URL
5+
const body = await request.json(); // 解析请求体
76

8-
if (!content) {
9-
return NextResponse.json({ error: '内容不能为空' }, { status: 400 });
7+
try {
8+
const response = await fetch(`${apiUrl}/submit`, { //向后端发送服务请求
9+
method: 'POST',
10+
headers: {
11+
'Content-Type': 'application/json',
12+
},
13+
body: JSON.stringify(body), // 将请求体发送到后端
14+
});
15+
//请求失败直接返回
16+
if (!response.ok) {
17+
return NextResponse.json({ error: 'Failed to submit data' }, { status: 500 });
1018
}
11-
12-
const client = await pool.connect(); // 获取数据库连接
13-
// 假设我们将内容插入到名为 'submissions' 的表中
14-
await client.query('INSERT INTO submissions (content) VALUES ($1)', [content]);
15-
client.release(); // 释放连接
16-
17-
return NextResponse.json({ message: '内容提交成功!' }, { status: 200 });
19+
//解析成功的响应
20+
const result = await response.json();
21+
return NextResponse.json({ message: 'Submission successful', data: result });
1822
} catch (error) {
19-
console.error('提交错误:', error);
20-
return NextResponse.json({ error: '内部服务器错误' }, { status: 500 });
23+
return NextResponse.json({ error: 'An error occurred while submitting data.' }, { status: 500 });
2124
}
2225
}

app/programs/[name]/[version]/page.tsx

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,12 @@ import SecurityAdvisories from '../../../../components/SecurityAdvisories';
1212
import BenchmarkResults from '../../../../components/BenchmarkResults';
1313
import VersionsSelector from '../../../../components/VersionsSelector';
1414
import { CrateInfo } from '@/app/lib/crate_info';
15-
1615
//异步获取依赖树
1716
async function fetchDependencyTree(name: string, version: string) {
1817
const response = await fetch(`/api/crates/${name}/${version}`);
1918
const versionData = await response.json();
2019

2120
const dependencies = versionData.dependencies || [];
22-
2321
const dependenciesDetails = await Promise.all(dependencies.map(async (subDep: { name: string; version: string; }) => {
2422
return fetchDependencyTree(subDep.name, subDep.version);
2523
}));

app/ui/programs/nav-links.tsx

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import { useState } from 'react';
1010
import Link from 'next/link';
1111
import { usePathname } from 'next/navigation';
1212
import clsx from 'clsx';
13+
import React from 'react';
14+
import { message } from 'antd';
1315

1416
// Map of links to display in the side navigation.
1517
// Depending on the size of the application, this would be stored in a database.
@@ -23,18 +25,17 @@ const links = [
2325
// { name: 'Customers', href: '/dashboard/customers', icon: UserGroupIcon },
2426
];
2527

26-
export default function NavLinks() {
28+
const NavLinks: React.FC = () => {
2729
const pathname = usePathname();
2830
const [isModalOpen, setModalOpen] = useState(false);
2931
const [inputValue, setInputValue] = useState('');
30-
3132
const [file, setFile] = useState<File | null>(null);
3233
const [isGithubLink, setIsGithubLink] = useState(true); // 控制输入类型
34+
const [messageApi, contextHolder] = message.useMessage();//antd-message的hooks调用
3335

3436
//暂定上传数据类型为react表单类型
3537
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
3638
e.preventDefault();
37-
3839
const formData = new FormData();
3940
if (isGithubLink) {
4041
formData.append('githubLink', inputValue);
@@ -44,29 +45,33 @@ export default function NavLinks() {
4445

4546
try {
4647
//用fetch向服务器发声POST请求,提交用户输入的内容
47-
const response = await fetch('/api/submi', { // 待替换为服务器API
48+
const response = await fetch('/api/submit', { //待替换为后端服务API
4849
method: 'POST',
49-
//请求体,将对象转换为json字符串
50+
//请求体
5051
body: formData,
5152
});
53+
//console.log('Response:', response); // 输出响应
54+
5255
//响应处理,根据响应结果显示提示信息,并重置输入框或关闭弹窗
5356
if (response.ok) {
54-
alert('内容提交成功!');//提交成功后重置输入框的值,并关闭弹窗
57+
messageApi.success('提交成功');//提交成功后重置输入框的值,并关闭弹窗
58+
console.log('提交成功');
5559
setInputValue('');
5660
setFile(null);
5761
setModalOpen(false);
5862
} else {
59-
alert('提交失败请重试。');
63+
messageApi.error('提交失败,请重试', 2);
6064
}
6165
} catch (error) {
62-
console.error('提交错误:', error);
63-
alert('提交失败,请检查网络连接。');
66+
messageApi.error('提交失败,请检查网络连接');
67+
//console.log('提交失败,请检查网络连接。', error);
6468
}
6569
};
6670

6771
//渲染部分
6872
return (
6973
<>
74+
{contextHolder}
7075
{links.map((link) => {
7176
const LinkIcon = link.icon;
7277
return (
@@ -185,4 +190,6 @@ export default function NavLinks() {
185190
)}
186191
</>
187192
);
188-
}
193+
}
194+
195+
export default NavLinks;

components/MessageContext.tsx

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// MessageContext.tsx
2+
import React, { createContext, useContext, ReactNode } from 'react';
3+
import { message } from 'antd';
4+
5+
// 定义消息上下文的类型
6+
interface MessageContextType {
7+
success: () => void;
8+
error: () => void;
9+
warning: () => void;
10+
}
11+
12+
// 创建上下文,默认值为 null
13+
const MessageContext = createContext<MessageContextType | null>(null);
14+
15+
// 定义 MessageProvider 的属性类型
16+
interface MessageProviderProps {
17+
children: ReactNode; // 允许任意子元素
18+
}
19+
20+
// 创建 MessageProvider 组件
21+
export const MessageProvider: React.FC<MessageProviderProps> = ({ children }) => {
22+
const success = () => {
23+
message.success('这是一个成功消息!');
24+
};
25+
26+
const error = () => {
27+
message.error('这是一个错误消息!');
28+
};
29+
30+
const warning = () => {
31+
message.warning('这是一个警告消息!');
32+
};
33+
34+
return (
35+
<MessageContext.Provider value={{ success, error, warning }}>
36+
{children}
37+
</MessageContext.Provider>
38+
);
39+
};
40+
41+
// 自定义 hook 使用上下文
42+
export const useMessage = () => {
43+
const context = useContext(MessageContext);
44+
if (!context) {
45+
throw new Error('useMessage must be used within a MessageProvider');
46+
}
47+
return context;
48+
};

layout.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import '@/app/ui/global.css';
22
import { inter } from '@/app/ui/fonts';
3-
3+
import React from 'react';
4+
import { message } from 'antd';
45

56
export default function RootLayout({
67
children,

0 commit comments

Comments
 (0)