graphql-fetch.ts 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import { type DocumentNode } from "graphql";
  2. import {
  3. type OperationVariables,
  4. ApolloClient
  5. } from "@apollo/client";
  6. import {GraphqlRequestResult} from "@/types/graphqlFetch/type";
  7. import {getClient} from "@/lib/ApolloClientServer";
  8. /* 定义自己的context类型
  9. import "@apollo/client";
  10. import { HttpLink } from "@apollo/client";
  11. declare module "@apollo/client" {
  12. interface DefaultContext extends HttpLink.ContextOptions {}
  13. }
  14. */
  15. // Comprehensive error handling example. https://www.apollographql.com/docs/react/data/error-handling
  16. export type CacheLifePreset =
  17. | "seconds"
  18. | "minutes"
  19. | "hours"
  20. | "days"
  21. | "weeks"
  22. | "max";
  23. export type CacheLifeOption = number | CacheLifePreset;
  24. export function getRevalidateTime(
  25. life?: CacheLifeOption
  26. ): number | false {
  27. if (!life) return false;
  28. if (typeof life === "number") return life;
  29. switch (life) {
  30. case "seconds":
  31. return 10;
  32. case "minutes":
  33. return 60;
  34. case "hours":
  35. return 3600;
  36. case "days":
  37. return 86400;
  38. case "weeks":
  39. return 604800;
  40. case "max":
  41. return false;
  42. default:
  43. return false;
  44. }
  45. }
  46. export function stableStringify(value: unknown): string {
  47. if (value === null || typeof value !== "object") {
  48. return JSON.stringify(value);
  49. }
  50. if (Array.isArray(value)) {
  51. return `[${value.map(stableStringify).join(",")}]`;
  52. }
  53. const obj = value as Record<string, unknown>;
  54. return `{${Object.keys(obj)
  55. .sort()
  56. .map(
  57. (key) => `"${key}":${stableStringify(obj[key])}`
  58. )
  59. .join(",")}}`;
  60. }
  61. export interface GraphQLRequestOptions {
  62. tags?: string[];
  63. life?: CacheLifeOption;
  64. noCache?: boolean;
  65. context?: Record<string, unknown>;
  66. fetchPolicy?:
  67. | "cache-first"
  68. | "network-only"
  69. | "no-cache"
  70. | "cache-only";
  71. }
  72. export async function graphqlRequest<
  73. TData = unknown,
  74. TVariables extends OperationVariables = OperationVariables
  75. >(
  76. query: DocumentNode,
  77. variables?: TVariables,
  78. options?: GraphQLRequestOptions
  79. ): Promise<GraphqlRequestResult<TData>> {
  80. const client = getClient();
  81. let resData;
  82. const revalidate = getRevalidateTime(options?.life);
  83. let queryOption: ApolloClient.QueryOptions<TData> = {
  84. query,
  85. variables,
  86. fetchPolicy: "network-only",
  87. context: {
  88. fetchOptions: {
  89. next: {
  90. revalidate,
  91. tags: options?.tags,
  92. },
  93. },
  94. }
  95. };
  96. if (options?.noCache) {
  97. /***
  98. * client.query的参数是一个对象:
  99. * {query, variables, context, fetchPolicy, errorPolicy}
  100. * context.fetchOptions 可以设置nextjs fetch的缓存策略 https://www.apollographql.com/docs/react/integrations/nextjs
  101. * context: {
  102. fetchOptions: {
  103. next: {
  104. revalidate: 60, // 对应 life: 'minutes'
  105. tags: ['posts'], // 对应 tags 选项
  106. },
  107. },
  108. },
  109. */
  110. queryOption = {
  111. query,
  112. variables,
  113. context: options?.context,
  114. fetchPolicy: "no-cache", // 跳过 apollo client 的缓存,直接调fetch
  115. };
  116. }
  117. if (options?.context) {
  118. throw new Error(
  119. "graphqlRequest: Caching with `context` is unsafe. Use noCache instead."
  120. );
  121. }
  122. try {
  123. // Promise-based APIs (e.g. client.query, client.mutate) - Errors either reject the promise or are returned in the result as the error field.
  124. // 如果错误被reject 则会进入catch
  125. const result: ApolloClient.QueryResult<TData> = await client.query(queryOption);
  126. resData = result.data || null;
  127. return {data: resData, error: result.error? result.error.message : '' };
  128. } catch (error) {
  129. throw error;
  130. }
  131. }
  132. export async function graphqlRequestNoCache<
  133. TData = unknown,
  134. TVariables extends OperationVariables = OperationVariables
  135. >(
  136. query: DocumentNode,
  137. variables?: TVariables,
  138. options?: Omit<
  139. GraphQLRequestOptions,
  140. "noCache" | "tags" | "life"
  141. >
  142. ): Promise<GraphqlRequestResult<TData>> {
  143. return graphqlRequest<TData, TVariables>(
  144. query,
  145. variables,
  146. {
  147. ...options,
  148. noCache: true,
  149. }
  150. );
  151. }