capacitor-community / http

Community plugin for native HTTP
MIT License
209 stars 135 forks source link

HttpResponse type generic #199

Open FernetB opened 2 years ago

FernetB commented 2 years ago

Is your feature request related to a problem? Please describe. I'm trying to stop using axios and use this package insteads, and found out that HttpResponse is not a generic type, because of that you can't type the data response.

Describe the solution you'd like Literally this

request<T = any>(options: HttpOptions): Promise<HttpResponse<T>>;
get<T = any>(options: HttpOptions): Promise<HttpResponse<T>>;
post<T = any>(options: HttpOptions): Promise<HttpResponse<T>>;
put<T = any>(options: HttpOptions): Promise<HttpResponse<T>>;
patch<T = any>(options: HttpOptions): Promise<HttpResponse<T>>;
del<T = any>(options: HttpOptions): Promise<HttpResponse<T>>;

export interface HttpResponse<T = any> {
  data: T;
  status: number;
  headers: HttpHeaders;
  url: string;
}

I do not have any problem on making the pr

mraible commented 2 years ago

If you make a PR for this, I'd be happy to test it out. I'm currently using the following code.

export class CapacitorHttpService implements Requestor {
  public async xhr<T>(settings: XhrSettings): Promise<T> {
    if (!settings.method) {
      settings.method = 'GET';
    }

    const response: HttpResponse = await Http.request({
      method: settings.method,
      url: settings.url,
      headers: settings.headers,
      data: settings.data,
    });
    return response.data as T;
  }
}

It works on iOS, but fails on Android with:

2022-05-09 14:13:30.745 14937-16415/io.ionic.starter I/System.out: org.json.JSONException: JSValue could not be coerced to JSObject.
2022-05-09 14:13:30.746 14937-16415/io.ionic.starter E/Capacitor/Plugin: JSONException
    org.json.JSONException: JSValue could not be coerced to JSObject.
        at com.getcapacitor.plugin.http.JSValue.toJSObject(JSValue.java:42)
        at com.getcapacitor.plugin.http.CapacitorHttpUrlConnection.setRequestBody(CapacitorHttpUrlConnection.java:193)
        at com.getcapacitor.plugin.http.HttpRequestHandler.request(HttpRequestHandler.java:395)
        at com.getcapacitor.plugin.http.Http$1.run(Http.java:83)
        at java.lang.Thread.run(Thread.java:920)