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

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


0

I would like to use dynamic cache. I was able to set the cache maxAge into the query resolver, but since the resolver can return both an unsuccessful and a successful response I would like to only cache the successful one. In order to do this I would like to set up the info cache value only for the SearchResultProductItem. This is my schema:

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!
}

Right now the resolver is like:

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
        },
      },

How can I write a resolver for the only SearchResultProductItem type?


Load 7 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *