request<TData, TVars> method

  1. @override
Stream<OperationResponse<TData, TVars>> request<TData, TVars>(
  1. OperationRequest<TData, TVars> operationRequest, [
  2. NextTypedLink<TData, TVars>? forward
])
override

A function called when a request reaches this TypedLink

Implementation

@override
Stream<OperationResponse<TData, TVars>> request<TData, TVars>(
  OperationRequest<TData, TVars> operationRequest, [
  forward,
]) {
  final operationType = getOperationDefinition(
    operationRequest.operation.document,
    operationRequest.operation.operationName,
  ).type;

  final fetchPolicy =
      operationRequest.fetchPolicy ?? defaultFetchPolicies[operationType];

  switch (fetchPolicy) {
    case FetchPolicy.NoCache:
      return _optimisticLinkTypedLink
          .request(operationRequest)
          .doOnData(_removeOptimisticPatch)
          .doOnCancel(() => cache.removeOptimisticPatch(operationRequest));
    case FetchPolicy.NetworkOnly:
      return _optimisticLinkTypedLink
          .request(operationRequest)
          .doOnData(_removeOptimisticPatch)
          .doOnData(_writeToCache)
          .doOnCancel(() => cache.removeOptimisticPatch(operationRequest));
    case FetchPolicy.CacheOnly:
      return _cacheTypedLink.request(operationRequest);
    case FetchPolicy.CacheFirst:
      return _cacheTypedLink.request(operationRequest).take(1).switchMap(
            (result) => result.data != null
                ? _cacheTypedLink.request(operationRequest)
                : _optimisticLinkTypedLink
                    .request(operationRequest)
                    .doOnData(_removeOptimisticPatch)
                    .doOnData(_writeToCache)
                    .doOnCancel(
                        () => cache.removeOptimisticPatch(operationRequest))
                    .switchMap(
                      (networkResponse) => ConcatStream([
                        Stream.value(networkResponse),
                        _cacheTypedLink.request(operationRequest).skip(1),
                      ]),
                    ),
          );
    case FetchPolicy.CacheAndNetwork:
      final sharedNetworkStream =
          _optimisticLinkTypedLink.request(operationRequest).shareValue();

      return MergeStream([
        _cacheTypedLink
            .request(operationRequest)
            .where((response) => response.data != null)
            .takeUntil(sharedNetworkStream),
        sharedNetworkStream
            .doOnData(_removeOptimisticPatch)
            .doOnData(_writeToCache)
            .doOnCancel(() => cache.removeOptimisticPatch(operationRequest))
            .concatWith([_cacheTypedLink.request(operationRequest).skip(1)])
      ]);
    default:
      throw Exception('Unrecognized FetchPolicy');
  }
}