How to Update Ember Model to Show JSON Search Response - json

I feel like this answer to this question is trivial, but I am having a difficult time figuring out how to do this the 'Ember way'.
Quick problem background: I am creating a recipe app with Ember frontend and a Rails API backend. I am implementing a search feature to find recipes based on ingredients. I have already configured my Rails API endpoint which sends back the correct records as JSON.
Ember.$.get('/recipes_query', {query: query})
.then(function(reponse) {
// Do something here
});
Now all I need to do is display these. What I am confused about is how to handle the data when it is retrieved (or in other words, how to push these to the store, and then ONLY show the most recently retrieved results). I could push these results to the store and then use a filter to display the correct results, but this seems like an extra step - the JSON response already contains everything I need to display. What is the Ember convention for performing this simple task?

It would be trivial answer if you would use query instead of jQuery.get, so if possible, refactor to:
this.store.query('recipe', {query: query})
.then(records => {
// you have everything you need as records
});

Related

Ember Data does not recognise ID in JSON response (inheritance-related)

I've been trying to figure this out for the past couple of hours and I thought it might be best to ask for some help at this point.
I am creating a new record (e.g., a new ProducerObjectiveOutcome record). The following error is being thrown after my Ember app posts data from a form to my Rails API:
Assertion Failed: Your outcome record was saved to the server, but the response does not have an id and no id has been set client side. Records must have ids. Please update the server response to provide an id in the response or generate the id on the client side either before saving the record or while normalizing the response.
What's strange is that my API is returning a JSON response with an ID (see below).
{
"producer_objective_outcome": {
"id":27,
"type":"ProducerObjectiveOutcome",
"title":"New outcome",
"owner": {
"id":6
}
}
}
As you might already have picked up, ProducerObjectiveOutcome is a subclass of Outcome.
In both my Ember App and Rails API, I have setup ProducerObjectiveOutcome to inherit from Outcome. In my Ember App particular, this is what the model looks like:
// app/models/producer-objective-outcome.js
import Outcome from "./outcome";
export default Outcome.extend({
});
Nothing fancy going on here – I thought it was all pretty straight forward – but for some reason, that error is coming up. I'm hoping one of you marvelous people can help me out with this!
Thanks in advance!
For anyone who is interested, I solved this by changing the name of the root node of the JSON response to outcome instead of it being producer_objective_outcome.
What may have helped in my earlier explanation is that the ProducerObjectiveOutcome record was being created at the following route: producer/objective/:id/outcome/new.
The key part of this URI, as I have figured just out, is the .../outcome/... section. I haven't tested otherwise, but given the conventions in Ember, I suspect that if that URI was .../producer-objective-outcome/... then everything would have been hunky dory.
TL;DR: the names in your JSON payload should match the route.

Non-standard JSON and Azure Logic Apps

I have an API that produces JSON like this:
)]}',
{
//JSON DATA
}
The //JSON DATA is valid JSON, but the )]}', up top is not.
When I try to GET this data via a Logic App, I get:
BadRequest. Http request failed: the content was not a valid JSON.
So, a few related questions:
1) Can I tell the logic app to return the invalid JSON anyway?
2) How can debug the issue better? I happen to know that the response is invalid, but what if I didn't? Can I see the raw data somewhere?
3) This is all done via the Azure web portal. Are there better tools? Visual Studio?
I should also mention that if I call a route on the same API that returns XML instead of JSON, then the Logic App works fine. So it definitely doesn't like the JSON response in particular.
Thanks!
First of all, please do not post three questions as a single question.
Question 1). The best thing you can do is make the API return a valid JSON object. This is good for million reasons. Here're a few:
it's pretty much a standard (either valid JSON or XML -- yeah, old school way);
therefore, no users of this API (including you) will need to struggle and guess what's going on and why;
your Logic App's step will just work without adding extra complexity;
you will make this world and your karma better.
If API-side changes are not within your reach, I don't think you can do much. If you're lucky and the HTTP action is successful (Status Code 2xx), you can try to use a Query Action with a function that truncates the first characters. It will look something like this (I don't know the exact syntax): #Substring(body('myHttpGet'), 4, length(body('myHttpGet')) - 4) where myHttpGet is the id of the Http Get action.
However, once again, if possible, I strongly recommend fixing up the API which is the root cause of the problem, instead of dealing with garbage response after that.
UPDATE Another thing you can do is wrap the dirty API. For example, you could create a trivial Azure Function that invokes the API you don't directly control, and sanitizes the response for you consumption requirements. This Azure Function function should be easy to call from the Logic App. It costs almost nothing (unless we're talking millions of requests/month). The only drawback here is the increasing latency, which may be not an issue at all -- test it and see whether it adds less than 100ms or so... Oh, and don't forget to file a ticket with the API owner, they make our world a bad place!
Question 2) In Azure Logic App web UI you can Look into the execution details and the error will definitely be there.
Question 3) You're asking for a tool recommendation which is by definition a highly subjective thing and is off-topic on StackOverflow.
TL/DR: The other app is not producing valid JSON.
Meaning, this is not a problem for you to solve. The other app has to return valid JSON if the owner claims it should.
If they cannot or will not produce valid JSON, then the first thing you need to do is inform your management that you will have to spend a lot of extra time accommodating their non-standard format.

ember.js with MySQL connection

I am trying to work out for a small ember application. What I want is to do is list all the items from a table of the MySQL DB. I am able to retrive and display the data from the localStorage of the ember store but I do not know how can I implement same thing using MySQL Database.
Any kind of help will be appriciated.
There are a few ways to do it, but basically you need some sort of server-side API to handle actually querying the MySQL database and returning data. This is usually done these days with a REST API using the interchange format JSON.
Whether you use PHP, Node, or another server technology, there are a couple of ways you can pull the data into Ember. Let's assume your have a server-side method called search, which returns a JSON array of blog posts, something like:
[
{"title": "blog post 1", "body": "this is a blog post"},
{"title": "blog post 2", "body": "this is another post"}
]
The easiest way to pull this data into Ember would be a simple ajax call:
var IndexRoute = Ember.Route.extend({
model: function()
{
return $.getJSON("http://apiurl.com/search");
}
});
In the above Ember route definition, the model is set to a function which returns the promise object returned by the JQuery getJSON method.
The template might look something like this:
<script type="text/x-handlebars" data-template-name="index">
{{#each}}
{{title}}<br/>
{{description}}
{{/each}}
</script>
Many Ember users choose to use EmberData instead of a ajax calls, however, that part of Ember is still under development and I found I had an easier time building my application without EmberData. Check out this article from one of the co-founders of Discourse:
http://eviltrout.com/2013/03/23/ember-without-data.html
The Ember Guides are pretty good place to start:
http://emberjs.com/guides/
http://emberjs.com/guides/routing/specifying-a-routes-model/
You can try Dreamfactory It's a SaaS REST API that will connect to a variety of SQL and NoSQL backends. I use it with SQL Server running on an RDS instance and haven't had any issues. I have written a super-basic, WIP Ember-Data adapter for it. It still needs a TON of work but is mostly functional.

Saving/Loading data from JSON to Phonegap/Kendo-UI App

First of all I'm very confused with this "JSON" thing, I can't completely get all the concepts but what I actually want to do is some kind of recipes Mobile Phonegap/kendo-UI(or whatever framework) App which should load data from JSON object. But I don't have a website where I could store data. So, what would be options to save and load data from JSON to my app? I mean it's very confusing to ask this, because I actually can't get the JSON, so I'am ready to get a lot of Dislikes but I want to know how to do a thing like that. I don;t know what URL to write and other stuff.
Hope someone will get what I acutally want and if this idea for loading data from JSON is not what I need, hope someone would like to offer other possibilities. Thank you.
Yes, you can technically save JSON files locally to your app, then retrieve that data locally. At the end of the day, it's not much different than getting it from a web service (other than the fact that it's going to be static data).
Not to get into too much detail here (This site has plenty of info), but JSON is a lightweight flavor of XML for passing data back and forth, very suitable for web services. All it is is key-value pairs. So, in your case, it'll be something like:
{ ["RecipeID" : 1,
"RecipeName" : "PB&J",
"RecipeIngredients" : ["Peanut butter", "Jelly", "Bread" ],
"RecipeDirections" : "If you really have to look this up on an app..."],
["RecipeID" : 2,
// ...
]
}
As you can see, it reads pretty clean and is easy to parse. So, in PhoneGap, you'd probably use jQuery and do something like,
$.getJSON("URLorLocationOfJSONfile", null, function(recipes) {
$.each(recipes, function(i,r) {
alert("Today, I'd like to eat... " + r.RecipeName);
)};
)};
And thus iterate through the JSON contents. Put them in a list or something. Whatever you'd like at that point. I build all my PhoneGap apps with JSON on the backend, so you're going in the right direction with that.
You can host the JSON file somewhere out there if you don't want to build an API for it, too. Just replace it when you get new recipes.
Hope that's a start.

JSON and changing datasets

I am fairly new to JSON and I want to create a choropleth example as so. http://gabrielflor.it/a-half-decade-of-rising-poverty Whenever the years are clicked it just goes to a different portion of the JSON (I'm assuming). Is this how functionality like this is usually done to avoid redrawing the whole map again and calling another JSON.js file? If so these .JSON files can get quite large?
Using a JSON is only a way to store values you need for each year. When you switch to another year the JS parse the JSON for the giving year and update the choropleth. For the example you have provided, here is the JSON used:
http://gabrielflor.it/static/data/saipe.json
This is a good way since you only have one JSON with every year you need and you load it only once. However since d3 needs datas this way I think you should add another JSON if you want to provide additional data like in gabrielflor example:
http://gabrielflor.it/static/js/d3.poverty-by-county.js?v=121107
He loads JSON like this with d3:
d3.json('../static/data/states.json', function (json) {
states = json;
});
or
d3.json('../static/data/saipehighlights.json', function (json) {
saipehighlights = json;
});
If you look at the network traffic for the example page you gave (ex. by using Chrome Developer Tools).
The file with the poverty data is quite large, but the mapping data file is even larger. You'll notice, that it takes longer for the website to load, but afterwords it runs very smoothly in the client without making any server calls.
The site is just about browsing information and nice design - for that purpose I think a longer load time is quite acceptable if the user experience after is smoother(i.e. user doesn't have to wait for year data to load).