I am pretty new to Ember. I have a service which returns a simple array like
[
"abc",
"bcd",
"cde",
"def",
"efg"
]
My model is somewhat like this
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
export default Model.extend({
value: attr()
});
In the serializer(I am trying with RESTSerializer), I want this data to be sent back to route.js where the service call is made. The service call is to an API which I am not allowed to change in any way.
I tried a lot of ways that might be stupid and googled a lot. Sadly I could not find a solution though I believe it may not be too tough.
I got the payload in serializer as pasted above and was able to log the response. From there what is to be returned and what serializer is apt is my current problem. Kindly ask me if any further details are required to figure this out. I am not posting much so that I can keep it simple and understandable. Any help is appreciated.
You may not want to use Ember Data. However, you can by implementing normalizeResponse in your Serializer.
For example, if your model name is "account":
export default DS.RESTSerializer.extend({
normalizeResponse(store, primaryModelClass, payload, id, requestType) {
let newPayload= {
accounts: [{
value: payload
}]
};
return this._super(store, primaryModelClass, newPayload, id, requestType);
}
});
Related
My Backend Rails API consumes POST requests in the form of
{
"name": "Mark White",
"email" : "mark#xyz.com"
}
Have tried this in Postman and this creates a record successfully.
In my ember frontend, Im using the following code to create a new record, from a form input:
app/routes/addUser.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
addUser(){
let formData = {
"name": this.controller.get('name'),
"email": this.controller.get('email')
};
let newUser = this.store.createRecord('user',formData);
newUser.save();
}
}
});
which generates the request as
{
"user": {
"name": "Mark White",
"email" : "mark#xyz.com"
}
}
which my backend is not prepared to handle and throws an error.
Any way I can quickly conform to the json format that works for me in Postman.
When the question is along the lines with the "How can I change my payload to server for it to be in a certain format?" then you should have a look at customizing a serializer.
But it looks like for solving your problem you might wanna take the standard JSON Serializer; in your app/serializers/application.js just type the following:
import JSONSerializer from '#ember-data/serializer/json';
export default class ApplicationSerializer extends JSONSerializer {
// ...
}
Note that it's for the Ember.js v4, according to your example you're using a bit older version so just adjust the syntax accordingly.
so I have a problem. My JSON data is getting sent over as a full string but its an object. How do i send an object instead of a string through my request. My reqparser is setup like this
search_parse = reqparse.RequestParser()
search_parse.add_argument('indexId', required=True, action='append')
search_parse.add_argument("pagination", required=False)
search_parse.add_argument("FilterCriteria", required=True)
and the JSON request I sent looks like this
{
"indexId": [
"testing"
],
"pagination": {
"Skip": 1,
"Take": 4
},
"FilterCriteria": {
"HasPatents": false,
"IsAuthor": false
}
}
and my payload is built up like this in my controller
sovren_payload = {
"PaginationSettings": pagination,
"IndexIdsToSearchInto": indexId,
"FilterCriteria": test
}
The problem I'm having is that the FilterCriteria is getting sent in the json as a string so this is how its supposed to look in JSON format
'FilterCriteria': {'coolguy': True, 'notcool': False}
But what I actually get is this
'FilterCriteria': "{'coolguy': True, 'notcool': False}"
How do I get rid of these annoying "" brackets in my json request. I print my sovren_payload and there it shows me the 'FileCriteria': "{random data}"
I also realise i have the same problem with the "pagination" variable. But if I fix it for FileCriteria I fix it for pagination as well.
Any insight would be greatly appreciated
Yeah okay, after 3 hours of struggling I found it out, should've put type=dict
I feel so stupid. My main language is C# and I only use python for AI stuff so its still new to me. Hope this helps some poor soul like me in the future :D
I'm working on a project using Ember/Ember-Data and there is a related/already existing service which is provide API with JSON response.
My project must interact with that service, but the response from that API is someting like below:
{ "id": 39402, "name": "My Name" }
or
[ {"id": 38492, "name": "Other Name" } ]
there is no person: or persons: that is required by Ember-Data compatable response.
How can I using this response on Ember-Data without change on the service or without build API gateway?
Ember-Data uses DS.RestAdapter, which in turn uses DS.RESTSerializer which extends from DS.JSONSerializer for serializing, extracting and massaging data that comes in from the server.
Since in your case you already have the data in your payload, all you need to do for reading the data is override extract method in the JSONSerializer which is actually quite simple.
If you are using ember-cli (which you should :)), your person.js file located inside your app/serializers directory would look as follows.
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
extract: function(store, primaryType, payload) {
return payload;
}
});
If you are not using ember-cli, you can do the following:
App.PersonSerializer = DS.JSONSerializer.extend({
extract: function(store, primaryType, payload) {
return payload;
}
});
I am getting JSON returned in this format:
{
"status": "success",
"data": {
"debtor": {
"debtor_id": 1301,
"key": value,
"key": value,
"key": value
}
}
}
Somehow, my RESTAdapter needs to provide my debtor model properties from "debtor" section of the JSON.
Currently, I am getting a successful call back from the server, but a console error saying that Ember cannot find a model for "status". I can't find in the Ember Model Guide how to deal with JSON that is nested like this?
So far, I have been able to do a few simple things like extending the RESTSerializer to accept "debtor_id" as the primaryKey, and also remove the pluralization of the GET URL request... but I can't find any clear guide to reach a deeply nested JSON property.
Extending the problem detail for clarity:
I need to somehow alter the default behavior of the Adapter/Serializer, because this JSON convention is being used for many purposes other than my Ember app.
My solution thus far:
With a friend we were able to dissect the "extract API" (thanks #lame_coder for pointing me to it)
we came up with a way to extend the serializer on a case-by-case basis, but not sure if it really an "Ember Approved" solution...
// app/serializers/debtor.js
export default DS.RESTSerializer.extend({
primaryKey: "debtor_id",
extract: function(store, type, payload, id, requestType) {
payload.data.debtor.id = payload.data.debtor.debtor_id;
return payload.data.debtor;
}
});
It seems that even though I was able to change my primaryKey for requesting data, Ember was still trying to use a hard coded ID to identify the correct record (rather than the debtor_id that I had set). So we just overwrote the extract method to force Ember to look for the correct primary key that I wanted.
Again, this works for me currently, but I have yet to see if this change will cause any problems moving forward....
I would still be looking for a different solution that might be more stable/reusable/future-proof/etc, if anyone has any insights?
From description of the problem it looks like that your model definition and JSON structure is not matching. You need to make it exactly same in order to get it mapped correctly by Serializer.
If you decide to change your REST API return statement would be something like, (I am using mock data)
//your Get method on service
public object Get()
{
return new {debtor= new { debtor_id=1301,key1=value1,key2=value2}};
}
The json that ember is expecting needs to look like this:
"debtor": {
"id": 1301,
"key": value,
"key": value,
"key": value
}
It sees the status as a model that it needs to load data for. The next problem is it needs to have "id" in there and not "debtor_id".
If you need to return several objects you would do this:
"debtors": [{
"id": 1301,
"key": value,
"key": value,
"key": value
},{
"id": 1302,
"key": value,
"key": value,
"key": value
}]
Make sense?
I have truly searched and I have not found a decent example of using the serializer to get objects from a differently formatted JSON response. My reason for not changing the format of the JSON response is outlined here http://flask.pocoo.org/docs/security/#json-security.
I'm not very good with javascript yet so I had a hard time understanding the hooks in the serialize_json.js or maybe I should be using mapping (I just don't know). So here is an example of my JSON response for many objects:
{
"total_pages": 1,
"objects": [
{
"is_completed": true,
"id": 1,
"title": "I need to eat"
},
{
"is_completed": false,
"id": 2,
"title": "Hey does this work"
},
{
"is_completed": false,
"id": 3,
"title": "Go to sleep"
},
],
"num_results": 3,
"page": 1
}
When ember-data tries to use this I get the following error:
DEBUG: -------------------------------
DEBUG: Ember.VERSION : 1.0.0-rc.1
DEBUG: Handlebars.VERSION : 1.0.0-rc.3
DEBUG: jQuery.VERSION : 1.9.1
DEBUG: -------------------------------
Uncaught Error: assertion failed: Your server returned a hash with the key total_pages but you have no mapping for it
Which totally makes when you look at my code for the data store:
Todos.Store = DS.Store.extend({
revision: 12,
adapter: DS.RESTAdapter.create({
mappings: {objects: "Todos.Todo"},
namespace: 'api'
})
});
My question is how do I deal with total_pages, num_results and page? And by deal, I mean ignore so I can just map the objects array.
All root properties you return in your JSON result are mapped to a DS.Model in Ember Data. You should not return properties that are not modelled or you should model them.
If you want to get rid of the error you should make an empty model for the properties you don't use.
Read more here
Why are you returning properties you don't want to use? Or is it out of your control?
The way to accomplish this is with a custom serializer. If all your data is returned from the server in this format you could simply create ApplicationSerializer like this:
DS.RESTSerilizer.extend({
normalizePayload: function(type, payload) {
delete payload.total_pages;
delete payload.num_results;
delete payload.page;
return payload;
}
});
That should allow Ember Data to consume your API seamlessly.
Ember is fairly opinionated about how things are done. Ember data is no exception. The Ember team works towards certain standards that it thinks is best, which is, in my opinion, a good thing.
Check out this post on where ember is going. TL;DR because there are so many varying implementations of api calls, they're setting their efforts towards supporting the JSON API.
From my understanding, there is no easy way to do what you're asking. Your best bet is to write your own custom adapter and serialized. This shouldn't be too hard to do, and has been done before. I recommend you having a look at the Tastypie adapter used for Python's Django Tastypie