示例#1
0
        public async Task can_hoist_response()
        {
            bool myCustomActionWasCalled = false;

            client.Configure(cf =>
            {
                cf.AfterCall = http =>
                {
                    myCustomActionWasCalled = true;
                    "AfterCall action set by user.".Dump();
                };
            });

            var list = await client
                       .AllowAnyHttpStatus()
                       .HoistResponse(out var responseGetter)
                       .Accounts
                       .ListAccountsAsync();

            var response = responseGetter();

            response.Should().NotBeNull();
            response.StatusCode.Should().NotBe(0);
            myCustomActionWasCalled.Should().BeTrue();
        }
        /// <summary>
        /// Setup the CoinbaseClient to use automatic token refresh.
        /// </summary>
        /// <param name="clientId">The OAuth Application Client ID</param>
        /// <param name="clientSecret">The OAuth Application Secret</param>
        /// <param name="onRefresh">Callback function to invoke when the OAuth token is refreshed.</param>
        public static CoinbaseClient WithAutomaticOAuthTokenRefresh(this CoinbaseClient client, string clientId, string clientSecret, Func <OAuthResponse, Task> onRefresh = null)
        {
            if (client.Config is OAuthConfig config)
            {
            }
            else
            {
                throw new InvalidOperationException($"Client must be using an {nameof(OAuthConfig)}");
            }

            async Task TokenExpiredErrorHandler(FlurlCall call)
            {
                var exception = call.Exception;

                if (exception is FlurlHttpException ex)
                {
                    var errorResponse = await ex.GetResponseJsonAsync <JsonResponse>().ConfigureAwait(false);

                    if (errorResponse.Errors.Any(x => x.Id == ExpiredToken))
                    {
                        var refreshResponse = await OAuthHelper.RenewAccessAsync(config.RefreshToken, clientId, clientSecret).ConfigureAwait(false);

                        config.AccessToken  = refreshResponse.AccessToken;
                        config.RefreshToken = refreshResponse.RefreshToken;

                        if (onRefresh is null)
                        {
                        }
                        else
                        {
                            await onRefresh(refreshResponse).ConfigureAwait(false);
                        }

                        call.Response = await call.Request.SendAsync(call.Request.Verb, call.HttpRequestMessage.Content).ConfigureAwait(false);

                        call.ExceptionHandled = true;
                    }
                }
            }

            client.Configure(s => s.OnErrorAsync = TokenExpiredErrorHandler);
            return(client);
        }