-2

In my project I'm calling a lot of WebApi with Refit (link). Basically, I define the WebApi as an interface. For example:

public interface ICustomer
{
    [Get("/v1/customer")]
    Task<CustomerResponse> GetDetails([Header("ApiKey")] string apikey, 
                                      [Header("Authorization")] string token, 
                                      [Header("Referer")] string referer);
}

For each WebApi, I create a client like that:

    public async Task<CustomerResponse> GetDetails(string apikey, string token)
    {
        CustomerResponse rsl = new CustomerResponse();
        rsl.Success = false;

        var customer = RestService.For<ICustomer>(apiUrl);
        try
        {
            rsl = await customer.GetDetails(apikey, token, apiUrl);
            rsl.Success = true;
        }
        catch (ApiException ax)
        {
            rsl.ErrorMessage = ax.Message;
        }
        catch (Exception ex)
        {
            rsl.ErrorMessage = ex.Message;
        }

        return rsl;
    }

The only difference between clients are the interface (in the above example code ICustomer), the return structure (in the example CustomerResponse derives from BaseResponse), and the function I have to call (in the example GetDetails with params).

I should have a base class to avoid duplicated code. Thanks in advance.

Enrico
  • 3,592
  • 6
  • 45
  • 102

1 Answers1

-1

I like when people gives you a negative feedback without any explanation or a solution. If someone has a similar problem of mine, it can find my generic class to resolve this problem.

public class BaseClient<T> where T : IGeneric
{
    public const string apiUrl = "<yoururl>";

    public T client;

    public BaseClient() : base() {
        client = RestService.For<T>(apiUrl);
    }

    public async Task<TResult> ExecFuncAsync<TResult>(Func<TResult> func) 
                               where TResult : BaseResponse
    {
        TResult rsl = default(TResult);

        T apikey = RestService.For<T>(apiUrl);
        try
        {
            rsl = func.Invoke();
            rsl.Success = true;
        }
        catch (ApiException ax)
        {
            rsl.ErrorMessage = ax.Message;
        }
        catch (Exception ex)
        {
            rsl.ErrorMessage = ex.Message;
        }

        return rsl;
    }

    public async Task<List<TResult>> ExecFuncListAsync<TResult>(Func<List<TResult>> func)
    {
        List<TResult> rsl = default(List<TResult>);

        T apikey = RestService.For<T>(apiUrl);
        try
        {
            rsl = func.Invoke();
        }
        catch (ApiException ax)
        {
        }
        catch (Exception ex)
        {
        }

        return rsl;
    }
}
Enrico
  • 3,592
  • 6
  • 45
  • 102