Ember/RSVP Promise value changes when passed to resolve() - ember.js

I am trying to wrap a jQuery AJAX request in a Ember RSVP promise, and I have this issue where the value I send to the resolve function (which is the jqXHR parameter) changes from object to string.
The code for doing the request + creating the request is as follows:
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax([URL], {
type: 'POST',
dataType: 'text'
}).then((data, textStatus, jqXHR) => {
console.log(jqXHR);
resolve(jqXHR);
}, (jqXHR, textStatus, errorThrown) => {
resolve(jqXHR);
});
});
And in my controller, I handle the request like this:
promise.then((response) => {
console.log(response);
if (response.status === 200) {
something...
} else {
something else...
}
receipt.set('busy', false);
});
Now, from the basic (and probably flawed) comprehension I have of RSVP.Promise, the resolve(jqXHR) line should send the jqXHR object as parameter to the callback, right?
Problem is, when I print the response I get in the console, all I get is 200 success, which is the body of the HTTP request I do.
However, when I print the jqXHR before resolving it, it correctly prints the whole object:
Object {readyState: 4, responseText: "200 success", status: 200, statusText: "OK"}
So why is this happening? Is Ember doing some wierd black magic and converts the jqXHR object to string? Or is the data string being sent in lieu of the jqXHR object I am expecting?
Thanks!

Got it!
Alright, so apparently rsvp.js checks if the object sent to the resolve method is 'thenable' (read then-able), i.e. if it contains a then method.
If it is 'thenable', it will execute the then method of the object, take its first argument (only) and take it as the fulfilled value. This little magic allows chaining resolves but doesn't work very well with callbacks that take multiple arguments.
So in my case, I was sending jqXHR to be resolved, which does contain a then method (according to the jQuery documentation). RSVP then tried to fulfill the jqXHR object as a promise, and returned the first argument of the resolve callback.
Now, the signature for the jqXHR resolve callback is function(data, textStatus, jqXHR);, which is why the object sent to MY callback was not jqXHR as I expected, but was the first argument of the jqXHR resolve callback: data.
TL;DR: Check if the object you try to resolve your promise with has a then method, because it WILL be executed.

Related

What is wrong with my timestamp in my MWS request?

If I submit a request to MWS via the scratchpad(AmazonServices/Scratchpad),
it is successful, and I am able to view the details of the successful request. In particular, the timestamp on the request looks like this:
&Timestamp=2018-08-14T18%3A30%3A02Z
If I literally take this timestamp, as is, and try to use it in my code to make the same exact request, I get an error:
<Message>Timestamp 2018-08-14T18%3A30%3A02Z must be in ISO8601
format</Message>\n
Here is the function I am trying to place it in: (some chars changed in sensitive params)
exports.sendRequest = () => {
return agent
.post('https://mws.amazonservices.com/Products/2011-10-01')
.query({
AWSAccessKeyId: encodeURIComponent('BINAJO5TPTZ5TTRLNGQA'),
Action: encodeURIComponent('GetMatchingProductForId'),
SellerId: encodeURIComponent('H1N1R958BK8TTH'),
SignatureVersion: encodeURIComponent('2'),
Timestamp: '2018-08-14T18%3A30%3A02Z',
Version: encodeURIComponent('2011-10-01'),
Signature: encodeURIComponent(exports.generateSignature()),
SignatureMethod: encodeURIComponent('HmacSHA256'),
MarketplaceId: encodeURIComponent('ATVPDKIKX0DER'),
IdType: encodeURIComponent('UPC'),
'IdList.Id.1': encodeURIComponent('043171884536')
})
.then(res => {
console.log('here is the response');
console.log(res)
})
.catch(error => {
console.log('here is the error');
console.log(error);
})
}
What is even more strange, is that this is the path the request is being sent to:
path: '/Products/2011-10-01?
AWSAccessKeyId=BINAJO5ZPTZ5YTTPNGQA&Action=GetMatchingProductForId&SellerId=H1N1R958ET8THH&SignatureVersion=2&Timestamp=2018-08-14T18%253A30%253A02Z&Version=2011-10-01&Signature=LwZn5of9NwCAgOOB0jHAbYMeQT31M6y93QhuX0d%252BCK8%253D&SignatureMethod=HmacSHA256&MarketplaceId=ATVPDKIKX0DER&IdType=UPC&IdList.Id.1=043171884536' },
The timestamp is not the same as the one I placed in the query. Why is this happening?
Your HTTP library is already doing the url-encoding for you, so you're double-encoding things. Remove all references to encodeURIComponent() and format your timestamp normally, with : and not %3A. Observe what happens to the generated URL.
Why? URL-encoding isn't safe to do repeatedly.
: becomes %3A with one pass, but it becomes %253A with a second pass, which is wrong.

ember-cli-mirage testing request params

I have default params that are added to the search request from a route. I would like to test these in ember-cli-mirage but am stuck on how to capture the request or requestBody so that I can assert against it.
Was looking for something similar to what I found on this SO post, but need access to the actual request and not the DOM. I am able to access the search params entered by the user (the 'text' param in my example) using currentUrl(), but the default params included in the request sent to the server, but not the url.
Is there a way to capture and assert against the request itself using ember-cli-mirage?
Something like
test('it appends default params to request'), function(assert) {
let searchUrl = '/my/route/url';
server.get(searchUrl, (db, request) => {
assert.equal(request.requestBody, "text=abc&all=true");
}
});
EDIT
I was able to get the test to pass using Qunit's async helper, like so:
test('it appends default params to athlete request', function(assert) {
assert.expect(2);
let done = assert.async();
server.get('/athletes', (db, request) => {
let params = request.queryParams;
assert.equal(params["page"], "1");
assert.equal(params["per"], "50");
done();
});
server.create('athlete', {first_name: 'John'});
visit('/athletes');
});
Still getting an error in the console for this test related to the json:api serialization:
normalizeResponse must return a valid JSON API document:
* meta must be an object
Going to open another question related to this failure elsewhere and link it in the comments.
The request param passed to your route handlers is the PretenderJS request object, which has some useful keys:
request.params, the dynamic segments of your route
request.queryParams, deserialized query request params
request.requestBody, the text body, You can use JSON.parse(request.requestBody) to turn this into an object.
So, if you wanted to assert against the query params, use request.queryParms.

How can i handle http requests failures with ember.js?

I've seen this question.
Until nothing is done for ember-data failures handling what can i write to patch it, so that i can have a message if my request doesn't have a 200OK response?
I'm looking at ember-data source code, for example, here's the createRecord function
createRecord: function(store, type, record) {
var root = this.rootForType(type);
var adapter = this;
var data = {};
data[root] = this.serialize(record, { includeId: true });
return this.ajax(this.buildURL(root), "POST", {
data: data
}).then(function(json){
Ember.run(adapter, 'didCreateRecord', store, type, record, json);
}, function(xhr) {
adapter.didError(store, type, record, xhr);
throw xhr;
});
}
I expected something like:
success: //do something
error: //do something else
But there's nothing like this. It's only a then after the ajax request.
What should I do? rewrite completely all the methods i need?
As of this commit ember data now uses promises (specifically the rsvp implementation), which replaces the success: and error: callbacks for a .then() style:
promise.then(function(value) {
// success
}, function(value) {
// failure
});
This is very similar to the previous callback style, but follows the promises style.
The first function is called on success and the second function is called on a failure. Looking at the code you posted shows that didError() is called on ajax failure, which is implemented in the adapter.
didError() (source) calls store.recordWasInvalid() if the status was 422, otherwise it calls store.recordWasError() (source).
store.recordWasInvalid() and store.recordWasError() transition the record into the isError or isValid = false state and triggers the becameError() and becameInvalid() events on the record. You can check these states or subscribe to these events to show your error message.

How should errors be handled when using the Ember.js Data RESTAdapter?

ember-data.js: https://github.com/emberjs/data/tree/0396411e39df96c8506de3182c81414c1d0eb981
In short, when there is an error, I want to display error messages in the view, and then the user can 1) cancel, which will rollback the transaction 2) correct the input errors and successfully commit the transaction, passing the validations on the server.
Below is a code snippet from the source. It doesn't include an error callback.
updateRecord: function(store, type, record) {
var id = get(record, 'id');
var root = this.rootForType(type);
var data = {};
data[root] = this.toJSON(record);
this.ajax(this.buildURL(root, id), "PUT", {
data: data,
context: this,
success: function(json) {
this.didUpdateRecord(store, type, record, json);
}
});
},
Overall, what is the flow of receiving an error from the server and updating the view? It seems that an error callback should put the model in an isError state, and then the view can display the appropriate messages. Also, the transaction should stay dirty. That way, the transaction can use rollback.
It seems that using store.recordWasInvalid is going in the right direction, though.
This weekend I was trying to figure the same thing out. Going off what Luke said, I took a closer look at the ember-data source for the latest commit (Dec 11).
TLDR; to handle ember-data update/create errors, simply define becameError() and becameInvalid(errors) on your DS.Model instance. The cascade triggered by the RESTadapter's AJAX error callback will eventually call these functions you define.
Example:
App.Post = DS.Model.extend
title: DS.attr "string"
body: DS.attr "string"
becameError: ->
# handle error case here
alert 'there was an error!'
becameInvalid: (errors) ->
# record was invalid
alert "Record was invalid because: #{errors}"
Here's the full walk through the source:
In the REST adapter, the AJAX callback error function is given here:
this.ajax(this.buildURL(root, id), "PUT", {
data: data,
context: this,
success: function(json) {
Ember.run(this, function(){
this.didUpdateRecord(store, type, record, json);
});
},
error: function(xhr) {
this.didError(store, type, record, xhr);
}
});
didError is defined here and it in turn calls the store's recordWasInvalid or recordWasError depending on the response:
didError: function(store, type, record, xhr) {
if (xhr.status === 422) {
var data = JSON.parse(xhr.responseText);
store.recordWasInvalid(record, data['errors']);
} else {
store.recordWasError(record);
}
},
In turn, store.recordWasInvalid and store.recordWasError (defined here) call the record (a DS.Model)'s handlers. In the invalid case, it passes along error messages from the adapter as an argument.
recordWasInvalid: function(record, errors) {
record.adapterDidInvalidate(errors);
},
recordWasError: function(record) {
record.adapterDidError();
},
DS.Model.adapterDidInvalidate and adapterDidError (defined here) simply send('becameInvalid', errors) or send('becameError') which finally leads us to the handlers here:
didLoad: Ember.K,
didUpdate: Ember.K,
didCreate: Ember.K,
didDelete: Ember.K,
becameInvalid: Ember.K,
becameError: Ember.K,
(Ember.K is just a dummy function for returning this. See here)
So, the conclusion is, you simply need to define functions for becameInvalid and becameError on your model to handle these cases.
Hope this helps someone else; the docs certainly don't reflect this right now.
DS.RESTAdapter just got a bit more error handling in this commit but we are still not yet at a point where we have a great recommendation for error handling.
If you are ambitious/crazy enough to put apps in production today with ember-data (as I have been!), it is best to make sure that the likelihood of failures in your API is extremely low. i.e. validate your data client-side.
Hopefully, we can update this question with a much better answer in the coming months.
I just ran into such a situation, not sure if this is already explained anywhere.
I am using:
Em.VERSION : 1.0.0
DS.VERSION : "1.0.0-beta.6"
Ember Validations (dockyard) : Version: 1.0.0.beta.1
Ember I18n
The model was initially mixedin with Validation mixin.
App.Order = DS.Model.extend(Ember.Validations.Mixin, {
.....
someAttribute : DS.attr('string'),
/* Client side input validation with ember-validations */
validations : {
someAttribute : {
presence : {
message : Ember.I18n.t('translations.someAttributeInputError')
}
}
}
});
In the template, corresponding handlebars is added. (note that ember validations will automatically add errors to model.errors.<attribute> in case of input validations, I will be using same trade-off in server validations as well)
<p>{{t 'translations.myString'}}<br>
{{view Ember.TextField valueBinding="attributeName"}}
{{#if model.errors.attributeName.length}}<small class="error">{{model.errors.attributeName}}</small>{{/if}}
</p
Now, we will be saving the Order
App.get('order').save().then(function () {
//move to next state?
}, function(xhr){
var errors = xhr.responseJSON.errors;
for(var error in errors){ //this loop is for I18n
errors[error] = Ember.I18n.t(errors[error]);
}
controller.get('model').set('errors', errors); //this will overwrite current errors if any
});
Now if there is some validation error thrown from server, the returned packet being used is
{"errors":{"attributeName1":"translations.attributeNameEror",
"another":"translations.anotherError"}}
status : 422
It is important to use status 422
So this way, your attribute(s) can be validated client side and again on server side.
Disclaimer : I am not sure if this is the best way!
Since there's currently no good solution in stock Ember-Data, I made my own solution by adding an apiErrors property to DS.Model and then in my RestAdapter subclass (I already needed my own) I added error callbacks to the Ajax calls for createRecord and updateRecord that save the errors and put the model in the "invalid" state, which is supposed to mean client-side or server-side validations failed.
Here's the code snippets:
This can go in application.js or some other top-level file:
DS.Model.reopen({
// Added for better error handling on create/update
apiErrors: null
});
This goes in the error callbacks for createRecord and updateRecord in a RestAdapter subclass:
error: function(xhr, textStatus, err) {
console.log(xhr.responseText);
errors = null;
try {
errors = JSON.parse(xhr.responseText).errors;
} catch(e){} //ignore parse error
if(errors) {
record.set('apiErrors',errors);
}
record.send('becameInvalid');
}

Display JSON response text from ajax in jQuery Template

I need to pass the response from ajax call to a jquery template.The response json is not malformed.I have checked this by using alert statements in the ajax fn.When the response is passed to the template,it does not get recognized.For example,when I use ${field1} in template,nothing gets displayed in the browser.No error messages are displayed at the browser.Can someone help me fix this issue?
Json response from server:
{
"field1": 23432434,
"field2": "sometext",
}
Ajax fn:
function getinfo(uri)
{
jQuery.ajax({
url: 'http://{{request.META.SERVER_NAME}}'+uri,
success: function(info) {
return info;
},
async: false,
dataType: 'jsonp'
});
}
Template:
<script id="infoTemplate" type="text/x-jQuery-tmpl">
<div>${field1}</div>
</script>
Code to Bind JSON to template:
<script id="Template1" type="text/x-jQuery-tmpl">
{{tmpl(getinfo(uri)) "#infoTemplate"}}
</script>
Note: I can't use the following method to bind JSON with template.That's a long story.
function getinfo(uri)
{
$.getJSON('http://{{request.META.SERVER_NAME}}'+uri, function(data) {
$("#infoTemplate").tmpl(data).appendTo("#somedivid");
});
}
That's not how callbacks work. You're returning info to the callback function, and not to getinfo.
You either have to do something like you proposed after, or keep the result from the ajax call in a global var and call the tmpl function after while, to be sure that you have already got the answer from the ajax call. The first way is the way to go.