Getting Type Error when using Ember Embedded Records Mixin with keyForAttribute - json

I've been banging my head against deserializing data with Ember. I feel like I've set it up right but I keep getting the same error. I'm trying to use the EmbeddedRecords Mixin, but it simply hasn't worked for me. Below is my debug data.
DEBUG: Ember : 1.6.1
DEBUG: Ember Data : 1.0.0-beta.7+canary.b45e23ba
DEBUG: Handlebars : 1.3.0
DEBUG: jQuery : 1.10.2
DEBUG: Model Fragments : 0.2.2
Here is a simple setup of what I've been doing. I have my model defined like this -
App.Subject = DS.Model.extend({
title: DS.attr('string'),
sections: DS.hasMany('section')
});
App.Section = DS.Model.extend({
title: DS.attr('string'),
subject: DS.belongsTo('subject')
});
App.SubjectSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
sections: { embedded: 'always' }
}
});
and here is the format of the JSON payload I'm sending for a 'show'
{
"subject": {
"_id":"549987b098909eef0ac2d691",
"title":"Maths",
"sections":[{
"title":"Precalc",
"_id":"549987b098909eef0ac2d693"
}, {
"title":"Calc",
"_id":"549987b098909eef0ac2d692"
}],"__v":0
}
}
I get the errors in the console
Error while processing route: subjects.show undefined is not a function TypeError: undefined is not a function
at Ember.Mixin.create.extractSingle (http://localhost:3300/js/highered.js:2043:25)
at apply (http://localhost:3300/js/highered.js:20664:27)
at superWrapper [as extractSingle] (http://localhost:3300/js/highered.js:20240:15)
at Ember.Object.extend.extractFind (http://localhost:3300/js/highered.js:4007:21)
at Ember.Object.extend.extract (http://localhost:3300/js/highered.js:3892:37)
at http://localhost:3300/js/highered.js:11864:34
at invokeCallback (http://localhost:3300/js/highered.js:23228:19)
at publish (http://localhost:3300/js/highered.js:22898:9)
at publishFulfillment (http://localhost:3300/js/highered.js:23318:7)
at http://localhost:3300/js/highered.js:28736:9
highered.js:16581 undefined is not a function TypeError: undefined is not a function
at Ember.Mixin.create.extractSingle (http://localhost:3300/js/highered.js:2043:25)
at apply (http://localhost:3300/js/highered.js:20664:27)
at superWrapper [as extractSingle] (http://localhost:3300/js/highered.js:20240:15)
at Ember.Object.extend.extractFind (http://localhost:3300/js/highered.js:4007:21)
at Ember.Object.extend.extract (http://localhost:3300/js/highered.js:3892:37)
at http://localhost:3300/js/highered.js:11864:34
at invokeCallback (http://localhost:3300/js/highered.js:23228:19)
at publish (http://localhost:3300/js/highered.js:22898:9)
at publishFulfillment (http://localhost:3300/js/highered.js:23318:7)
at http://localhost:3300/js/highered.js:28736:9
Which as best I can tell is directly related to extractSingle at the this.keyForAttribute method
extractSingle: function(store, primaryType, payload, recordId, requestType) {
var root = this.keyForAttribute(primaryType.typeKey),
partial = payload[root];
updatePayloadWithEmbedded(store, this, primaryType, partial, payload);
return this._super(store, primaryType, payload, recordId, requestType);
},
although an interesting thing to note is that the error occurs at extractArray when I am using the subjects index route, which return the json above but with array brackets as well.
extractArray: function(store, type, payload) {
var root = this.keyForAttribute(type.typeKey),
partials = payload[pluralize(root)];
forEach(partials, function(partial) {
updatePayloadWithEmbedded(store, this, type, partial, payload);
}, this);
return this._super(store, type, payload);
}
Which makes me think that Ember Data is having trouble recognizing the format. This happens any time I define a serializer for a model, not just when I enable embedded records.
I'm hoping someone will be able to explain this. As a final note I've been using the Ember Data Model Fragments library as well, but I disabled that and still got this error so I don't think that is it.

The Embedded Records mixin doesn't work with the RESTSerializer before beta 9.
You can view the state of it here Ember-data embedded records current state?
You'll also want to be wary of updating ember or ember data without the other version in certain circumstances. Ember Data cannot read property 'async' of undefined

Related

How to map over json array in react native?

hello everyone i want to render the json response returned from server for that i'm using map method. But there is a mistake in my code please help me to figure it..The response i'm getting is
response.json
{
status: true
token:{
access_token: "BhTErqRtliUG#8"
client_id: "ck4fLr08YHkW2y"
expires: "2018-02-19 03:51:50"
scope: null
user_id:465
},
user:{
avatar: "https://www.indianeconomy.net/lms/wp-content/uploads/2017/11/favicon.png"
email: "tet#wehubs.afs"
id:465
name: "testere"
sub:""
}
}
I've tried this
fetch(''{
.... }).then((responseData)=>{
this.setState({
userdetail: responseData,
loaded:true,
})
}
render(){
return this.state.userdetail.map(user=>{
<Text>{token.access_token}</Text>
})
}
How to use map method over above json response?
The other comments are correct. You cannot map over an object like this. There are ways you can iterate over object properties:
for(let prop in object) {
console.log(object[prop]);
}
However, in your example the objects don't have any similarities so you would not get any benefit from iterating over them.
If instead, you wanted to display the access token, you would do the following:
return (
<Text>{this.state.userdetail.token.access_token}</Text>
);
json string shown by you is not a valid json you can validate here https://jsonlint.com/
i am not sure about react but you mention dict so in python if you have valid json
you can map it with dict like this
json.loads(json_string)

JSON data fails to map to my exported interface?

I can't bind my Angular HTML to my devices array because there is a mismatch between what I am expecting the object to look like. I want to bind to device.modelName but it fails because the object I'm actually getting back has the property ModelName without camelCase!
Googling a solution I saw that I should use type assertion so I did by adding <DeviceStatus[]> resulting in the line <DeviceStatus[]>response.json()); in my component class. Unfortunately this didn't seem to change anything.
Why does it seem like my json object isn't being mapped properly?
My model interface:
export interface DeviceStatus {
deviceId: string;
modelName: string;
}
My component:
export class FetchDataComponent {
public devices: Observable<DeviceStatus[]>;
constructor(http: Http) {
this.devices =
http.get('api/Devices')
.map((response: Response) => <DeviceStatus[]>response.json());
this.devices.subscribe(x => console.log(x));
}
}
The result in Chrome console:
(2) [Object, Object]
0: Object
DeviceId: "1"
ModelName: "Model Name"
...
Type assertion only informs the compiler, it does nothing to the actual data as it says in the docs:
A type assertion is like a type cast in other languages, but performs
no special checking or restructuring of data
Always remember that the type system in typescript doesn't get translated to javascript, so in runtime you don't have that.
You'll need to do the convertion yourself:
this.devices =
http.get('api/Devices')
.map((response: Response) => response.json().map(device => ({
deviceId: device.DeviceId,
modelName: device.ModelName
}));
Here is the ASP.NET code using the formatter:
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver=
new CamelCasePropertyNamesContractResolver();
It converts the properties to camel case before returning them in the response.
You can find out more about it here: http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Serialization_CamelCasePropertyNamesContractResolver.htm
And there is a more complete example in this post here: Web API 2: how to return JSON with camelCased property names, on objects and their sub-objects

Ember Serializer works for Mirage but not with real data

I am new to Ember and is trying to create a small application using version beta 2.3.0.
Provided a country and zipcode, I am trying to get the city and zipcode.
With Mirage and a custom serializer (I am using the same format as of real json) my code works perfectly.
However, with the real API, the Promise remains in Pending state. There is no error in console.
And the logs in my serializer does not display when using real service indicating that the serializer is not executing.
Has anyone faced a similar issue before. Please help.
In my controller, I am finding the record as:
this.store.find('address', zipcode).then(
function(address) {
console.log("Hello Got Address");
});
My adapters/application.js :
export default DS.RESTAdapter.extend({
host: 'http://real_url_here',
pathForType: function(type) {
return '';
}});
The JSONAPISerialier is overriden in serializers/application.js as:
export default DS.JSONAPISerializer.extend({
normalizeResponse(store, primaryModelClass, payload, id, requestType) {
.......... // Code goes here
}});
In my mirage/config.js, I am returning sample json for 2 zipcodes and at the end I have added:
this.passthrough('http://real_url_here/**');
to invoke real service for other zipcodes
I got the answer finally :).
I had to disable the mirage in development :
To disable in development,
// config/environment.js
...
if (environment === 'development') {
ENV['ember-cli-mirage'] = {
enabled: false
}}

ember 1.12 findAll issue using rest, pod model over json response

I have a Rest adapter right configured and when I try:
router.js
export default Ember.Route.extend({
model: function() {
return this.store.find('main.user');
}
});
I got this:
WARNING: Encountered "main.user" in payload, but no model was found
for model name "mainUser" (resolved model name using
plezure#serializer:-rest:.typeForRoot("main.user"))
Error while processing route:
main.user Assertion Failed: The response from a findAll must be an
Array, not undefined Error: Assertion Failed: The response from a
findAll must be an Array, not undefined
My Json return:
{
"main.user": [
{ "id": "1", "name": "foo" },
{ "id": "2", "name": "bar" }
]
}
model.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string')
});
My pod are right configured, everything is fine, all works if I change to the find to a non-pod model, like this (model exists at main/):
export default Ember.Route.extend({
model: function() {
return this.store.find('main');
}
});
But with 'main.user' ember is uncapable to deal with json return, using fixtures pod names works well, it's ony happens on json response.
Anyone have any ideia about this kind of issue?

parse urls in Backbone.js

I am new to Backbones.js, and I was trying to get my JSON urls and parse them correctly.
This is my code:
window.Post = Backbone.Model.extend({
initialize: function(options) {
this.id = options.id;
},
url: function() {
return 'api/get_post/?post_type=movies&id=' + this.id;
},
parse : function(response) {
return response.posts;
},
});
window.Posts = Backbone.Collection.extend({
model: Post,
defaults: {
model: Post,
},
url: "api/get_recent_posts/?post_type=movies",
parse : function(response) {
return response.posts;
},
});
It seems that parsing for both overrides each other or something. when I remove the parse option from the Post class, I get a full response from the collection, but not from the model.
Are there any clear examples on how to set parsing for different son hierarchies? my JSON result have a status ok before it dives into the actual data.
I've never used bones.js but maybe these examples will help.
I think what you want to do is get rid of the parse() function in your collection. This assumes that since it is a Post collection, your data will come in as an array of Post JSON objects [{id:'1', 'sub':{data}},{id:'2', 'sub':{data}},{id:'3', 'sub':{data}}] or something like that.
If your Post model has sub-models or collections, your model parse() will then take the sub-object property name and do something with it.
// In Post Model definition
parse:function(response) {
if (response.sub) {
// create some model or collection etc.
}
}
You might have to pass an option parse:true when you do your collection fetch.
I posted something along these lines which might help you see how sub-models can be instantiated on fetch calls.
Backbone.js: Load multiple collections with one request
Cast/initialize submodels of a Backbone Model
I hope this helps.