Open
Description
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!
});
Metadata
Metadata
Assignees
Labels
No labels
Activity