paper-ai-release-24-07-21/components/GetSemantic.tsx

70 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-01-18 15:46:18 +08:00
import axios from "axios";
import { getRandomOffset } from "@/utils/others/quillutils";
2024-01-18 15:46:18 +08:00
interface Author {
authorId: string;
name: string;
}
interface Paper {
paperId: string;
title: string;
abstract: string;
year: number;
authors: Author[];
venue: string;
2024-01-18 23:22:23 +08:00
url: string;
2024-01-18 15:46:18 +08:00
}
2024-02-18 12:10:53 +08:00
async function getSemanticPapers(
query: string,
year: string,
offset = -1,
limit = 2
) {
2024-01-18 15:46:18 +08:00
try {
2024-02-13 15:12:48 +08:00
const maxOffset = 20 - limit; // 假设总记录数为 20
2024-02-18 12:10:53 +08:00
if (offset === -1) offset = getRandomOffset(maxOffset);
2024-01-18 15:46:18 +08:00
const url = `https://api.semanticscholar.org/graph/v1/paper/search`;
const response = await axios.get(url, {
headers: {
"x-api-key": process.env.NEXT_PUBLIC_SEMANTIC_API_KEY,
2024-01-18 15:46:18 +08:00
},
params: {
query: query,
offset: offset,
limit: limit,
2024-01-18 15:46:18 +08:00
year: year,
2024-01-19 15:36:41 +08:00
fields: "title,year,authors.name,abstract,venue,url,journal",
2024-01-18 15:46:18 +08:00
},
});
// 提取并处理论文数据
const papers = response.data.data.map((paper: Paper) => {
2024-01-18 15:46:18 +08:00
// 提取每篇论文的作者名字
const authorNames = paper.authors.map((author) => author.name);
return {
...paper,
authors: authorNames, // 替换原有的authors字段为仅包含名字的数组
};
});
return papers;
} catch (error: any) {
// console.error("Error fetching data from Semantic Scholar API:", error);
throw new Error(
`Error fetching data from Semantic Scholar API:${JSON.stringify(
error.response,
null,
2
)}`
);
// return null;
2024-01-18 15:46:18 +08:00
}
}
// 调用函数示例
// fetchSemanticPapers("covid", 50, 2, "2015-2023").then((data) => {
// console.log(data);
// });
export default getSemanticPapers;