createMiddleware method

Middleware<T> createMiddleware()

Implementation

Middleware<T> createMiddleware() {
  return (Store<T> store, dynamic action, NextDispatcher next) {
    if ((action is APIAction)) {
      APIAction castAction = action;
      castAction.apiCall(store.state.networkState).then((Response response) {
        if (response.statusCode >= 200 && response.statusCode < 300) {
          store.dispatch(ResponseAction(
              response: response,
              dispatcherKey: castAction.dispatcherKey,
              decodeResponse: castAction.decodeResponse,
              networkCompletionKey: castAction.networkCompletionKey));
        } else {
          // this is an API error
          String errorBody = response.body;
          if (errorBody.isEmpty) {
            store.dispatch(ApiErrorAction(
                ApiError.fromJson('{"status": ${response.statusCode}}')!,
                networkCompletionKey: castAction.networkCompletionKey,
                originAction: action));
          } else {
            store.dispatch(ApiErrorAction(ApiError.fromJson(response.body)!,
                networkCompletionKey: castAction.networkCompletionKey,
                originAction: action));
          }
        }
      });
    }
    if ((action is ResponseAction)) {
      ResponseAction castAction = action;
      castAction.dispatchDecodeResponse(store);
    }
    next(action);
  };
}