Skip to content

Allow multiple arguments to reject(); #531

Open
@izelnakri

Description

@izelnakri
import RSVP from 'rsvp';
import Service from '@ember/service';
import { inject as service } from '@ember/service';

export default Service.extend({
  post(url, data, headers) {
    return new RSVP.Promise((resolve, reject) => {
      return fetch(buildUrl(url), {
        method: 'POST', mode: 'no-cors', headers: this.buildHeaders(headers),
        body: JSON.stringify(data)
      }).then((response) => prepareResponsesFor(201, response, resolve, reject));
    });
  },
  buildHeaders(headers) {
    const authHeader = this.get('session.authenticationToken') ? {
      'Authorization': `Bearer ${this.get('session.authenticationToken')}`
    } : {};

    return Object.assign({}, authHeader, { 'Content-Type': 'application/json' }, headers);
  }
});

function prepareResponsesFor(statusCode, response, resolve, reject) {
  return response.json().then((json) => {
    return response.status === statusCode ? resolve(json, response) : reject(json, response);
  });
}

function buildUrl(url) {
  return url.startsWith('/') ? `${ENV.APP.API_HOST}${url}` : url;
}

usage:

this.get('fetch').post('/login', { email: email, password: password }).catch((json, response) => {
  console.log(json); // returns the object
  console.log(response); // undefined!
});

=======================
It took me hours to realize reject() implementation ignores the second argument. Currently as a workaround I do this:

return initialResponse.json().then((json) => {
    return response.status === statusCode ? resolve(json, response) : reject([json, response]);
  });

usage:

this.get('fetch').post('/login', { email: email, password: password }).catch(([json, response]) => {
  console.log(json); // returns the object
  console.log(response); // gets the response!
});

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions