Apollo GraphQL:动态缓存模式类型,而不是整个解析器

Apollo GraphQL: dynamically caching a schema type, not the entire resolver

提问人:sharkbait 提问时间:10/31/2023 最后编辑:sharkbait 更新时间:11/3/2023 访问量:14

问:

我想使用动态缓存。我能够将缓存 maxAge 设置到查询解析器中,但由于解析器可以同时返回不成功和成功的响应,因此我只想缓存成功的响应。为此,我想仅为 SearchResultProductItem 设置信息缓存值。这是我的架构:

type SearchResultSuccessfulResponse {
  "Set true false for the response of the API"
  success: Boolean!
  searchResult: SearchResult!
}

union SearchProductsResponse = GenericResponse | SearchResultSuccessfulResponse

type SearchResult {
  searchResultItem: [SearchResultProductItem!]!
}

"Product details"
type SearchResultProductItem {
  "Product id"
  globalMaterialID: ID!
}

type Query {
  "Search products"
  searchProducts(searchRequest: SearchRequest!): SearchProductsResponse!
}

现在解析器是这样的:

Query: {
        searchProducts: async (_, args: QuerySearchProductsArgs, context, info) => {
          // info.cacheControl.setCacheHint({ maxAge: context.cacheMaxAge, scope: "PRIVATE" })
          try {
            const result = await (context.datasourceApiMap[ProductAPI.apiName] as ProductAPI).searchProducts(
              args.searchRequest,
            )
            return {
              success: true,
              searchResult: result,
            }
          } catch (error: any) {
            return {
              success: false,
              errorCode: (error.extensions && error.extensions.code) ?? "PRODUCTS_NOT_FOUND",
              errorMessage: error.message,
            }
          }
        },
      },
      SearchProductsResponse: {
        __resolveType(response) {
          if (response.success) {
            return "SearchResultSuccessfulResponse"
          }
          if (!response.success) {
            return "GenericResponse"
          }
          return null
        },
      },

如何为唯一的 SearchResultProductItem 类型编写解析程序?

缓存 graphql apollo-server 解析器

评论

0赞 Michel Floyd 11/1/2023
很难理解你已经分层到一个本应是简单查询的所有不必要的复杂性。如果在外部 API 失败时只是 GraphQL 错误,则不会缓存该结果。您永远不需要在结果中使用指标。throwsuccess

答: 暂无答案