From e3722dc329fec338f557c501420ce21d3238b0a7 Mon Sep 17 00:00:00 2001 From: JimmyLv Date: Mon, 27 Feb 2023 21:08:03 +0800 Subject: [PATCH] fix: add fetchWithTimeout --- pages/[...slug].tsx | 3 ++- utils/fetchWithTimeout.ts | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 utils/fetchWithTimeout.ts diff --git a/pages/[...slug].tsx b/pages/[...slug].tsx index dcddcd40..5758a402 100644 --- a/pages/[...slug].tsx +++ b/pages/[...slug].tsx @@ -8,6 +8,7 @@ import { useLocalStorage } from "react-use"; import Footer from "../components/Footer"; import Header from "../components/Header"; import SquigglyLines from "../components/SquigglyLines"; +import { fetchWithTimeout } from "../utils/fetchWithTimeout"; export const Home: NextPage = () => { const router = useRouter(); @@ -49,7 +50,7 @@ export const Home: NextPage = () => { router.replace(curUrl); } setLoading(true); - const response = await fetch("/api/summarize", { + const response = await fetchWithTimeout("/api/summarize", { method: "POST", headers: { "Content-Type": "application/json", diff --git a/utils/fetchWithTimeout.ts b/utils/fetchWithTimeout.ts new file mode 100644 index 00000000..f999b786 --- /dev/null +++ b/utils/fetchWithTimeout.ts @@ -0,0 +1,20 @@ +interface Options extends RequestInit { + /** timeout, default: 8000ms */ + timeout?: number +} + +export async function fetchWithTimeout( + resource: RequestInfo | URL, + options: Options = {} +) { + const { timeout } = options + + const controller = new AbortController() + const id = setTimeout(() => controller.abort(), timeout) + const response = await fetch(resource, { + ...options, + signal: controller.signal + }) + clearTimeout(id) + return response +}