restApiClient.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use client';
  2. /**前端客户端组件调rest api 接口 */
  3. import { getSession } from "next-auth/react";
  4. import { getCartToken } from "@/utils/getCartToken";
  5. import { BagistoSession } from "@/types/types";
  6. let sessionCache: { session: BagistoSession | null; timestamp: number } | null = null;
  7. const SESSION_CACHE_TTL = 5000;
  8. async function getCachedSession(): Promise<BagistoSession | null> {
  9. const now = Date.now();
  10. if (sessionCache && now - sessionCache.timestamp < SESSION_CACHE_TTL) {
  11. return sessionCache.session;
  12. }
  13. //When called, getSession() will send a request to /api/auth/session and returns a promise with a session object, or null if no session exists.
  14. const session = (await getSession()) as BagistoSession | null;
  15. sessionCache = { session, timestamp: now };
  16. return session;
  17. }
  18. export async function clientFetch(apiUrl: string, options: RequestInit) {
  19. // 请求的是nextjs的代理接口
  20. const session = await getCachedSession();
  21. const userToken = session?.user?.accessToken;
  22. const guestToken = !userToken ? getCartToken() : null;
  23. const token = userToken || guestToken;
  24. const headers = {
  25. ...(token && { Authorization: `Bearer ${token}` }),
  26. "Content-Type": "application/json",
  27. };
  28. if(options.headers) {
  29. options.headers = Object.assign(headers, options.headers);
  30. } else {
  31. options.headers = headers;
  32. }
  33. const response = await fetch(apiUrl, options);
  34. // console.log('response -- ', response);
  35. if(response.ok) {
  36. const result = await response.json();
  37. return result;
  38. } else {
  39. return {
  40. status: response.status,
  41. statusText: response.statusText,
  42. data: await response.text(),
  43. }
  44. }
  45. }