SpoonX / aurelia-api

A simple convenience wrapper around aurelia-fetch-client
http://aurelia-api.spoonx.org
MIT License
72 stars 21 forks source link

Expose response object from fetch call #198

Closed Kukks closed 6 years ago

Kukks commented 7 years ago

Exposing the actual Response object after a successful fetch would add unlimited flexibility to handling the response outside of the body(e.g. response headers as we talked about on Gitter @RWOverdijk ).

Maybe we can change the request(method: string, path: string, body?: {}, options?: {}): Promise<any|Error> signature to request(method: string, path: string, body?: {}, options?: {}, responseOutput?: { response: Response}): Promise<any|Error> and all wrapper functions that use it?

so the impl would be something like:

 request(method: string, path: string, body?: {}, options?: {}, responseOutput?: { response: Response}): Promise<any|Error> {
    let requestOptions = extend(true, {headers: {}}, this.defaults, options || {}, {method, body});
    let contentType    = requestOptions.headers['Content-Type'] || requestOptions.headers['content-type'];

    if (typeof body === 'object' && body !== null && contentType) {
      requestOptions.body = (/^application\/json/).test(contentType.toLowerCase())
                          ? JSON.stringify(body)
                          : buildQueryString(body);
    }

    return this.client.fetch(path, requestOptions).then((response: Response) => {
      if (response.status >= 200 && response.status < 400) {
        if(responseOutput){
          responseOutput.response = response;
        }       
        return response.json().catch(() => null);
      }

      throw response;
    });
  }