using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; namespace Octokit.Reactive.Internal { public static class ConnectionExtensions { public static IObservable GetAndFlattenAllPages(this IConnection connection, Uri url) { return GetPages(url, null, (pageUrl, pageParams) => connection.Get>(pageUrl, null, null).ToObservable()); } public static IObservable GetAndFlattenAllPages(this IConnection connection, Uri url, ApiOptions options) { return connection.GetAndFlattenAllPages(url, null, options); } public static IObservable GetAndFlattenAllPages(this IConnection connection, Uri url, IDictionary parameters) { return GetPages(url, parameters, (pageUrl, pageParams) => connection.Get>(pageUrl, pageParams, null).ToObservable()); } public static IObservable GetAndFlattenAllPages(this IConnection connection, Uri url, IDictionary parameters, ApiOptions options) { return GetPagesWithOptions(url, parameters, options, (pageUrl, pageParams, o) => { var passingParameters = Pagination.Setup(parameters, options); return connection.Get>(pageUrl, passingParameters, null).ToObservable(); }); } public static IObservable GetAndFlattenAllPages(this IConnection connection, Uri url, IDictionary parameters, string accepts) { return GetPages(url, parameters, (pageUrl, pageParams) => connection.Get>(pageUrl, pageParams, accepts).ToObservable()); } static IObservable GetPages(Uri uri, IDictionary parameters, Func, IObservable>>> getPageFunc) { return getPageFunc(uri, parameters).Expand(resp => { var nextPageUrl = resp.HttpResponse.ApiInfo.GetNextPageUrl(); return nextPageUrl == null ? Observable.Empty>>() : Observable.Defer(() => getPageFunc(nextPageUrl, null)); }) .Where(resp => resp != null) .SelectMany(resp => resp.Body); } static IObservable GetPagesWithOptions(Uri uri, IDictionary parameters, ApiOptions options, Func, ApiOptions, IObservable>>> getPageFunc) { return getPageFunc(uri, parameters, options).Expand(resp => { var nextPageUrl = resp.HttpResponse.ApiInfo.GetNextPageUrl(); var shouldContinue = Pagination.ShouldContinue(nextPageUrl, options); return shouldContinue ? Observable.Defer(() => getPageFunc(nextPageUrl, null, null)) : Observable.Empty>>(); }) .Where(resp => resp != null) .SelectMany(resp => resp.Body); } } }