EmberJS Model Array - ember.js

Is there any way to define arrays on EmberJS models? I saw some posts using Transformation but those approaches don't achieve the results I need.
This is the (json) model I'm trying to represent:
{
"category" : "Category 1",
"subcategories" : [
{
"name" : "subcategory1",
"value" : 210
},
{
"name" : "subcategory2",
"value" : 220
}
]
},
{
"category" : "Category 2",
"subcategories" : [
{
"name" : "subcategory21",
"value" : 250
},
{
"name" : "subcategory22",
"value" : 270
}
]
}
I read about the hasMany method but I understand that it's only for relationships. If so, how can I represent that example json as ember model?
Thanks for the help!

For those that are having the same doubt/issue:
http://thejsguy.com/2016/01/29/working-with-nested-data-in-ember-data-models.html

Related

Category labels having brackets([]) are not showing complete label

In am chart, labels having square bracket in it are ignoring the content between [] brackets on category axis . I checked and ensured that they are passed as string instead of array, even I tried to return this as html ,that also did not worked out for me
Now I am expecting the label to be shown completely irrespective of its content when it is string. Can any one suggest some ways to overcome this .Thanks in advance
My code:
am4core.useTheme(am4themes_animated);
var config = {
yAxes: [
{
id: "c1",
type: "CategoryAxis",
dataFields : {
category : "country"
},
renderer : {
minGridDistance : 20,
minWidth : 120,
grid : [{
location : 0
}]
}
}
],
xAxes: [
{
id: "v1",
type: "ValueAxis",
dataFields : {
value : "visits"
},
renderer : {
maxLabelPosition : 0.98
}
}
],
series: [
{
type: "ColumnSeries",
name: "Series Title",
dataFields: {
valueX: "visits",
categoryY: "country"
},
sequencedInterpolation : true,
sequencedInterpolationDelay : 100,
adapter : {
tooltipText : function(val) {
return 'hello' + val // doesn't work?
}
},
columns : [
{
strokeOpacity : 1, // has no effect?
template : {
adapter : {
"fill" : function (fill, target) {
return target.dataItem.index // not quite right
}
}
}
}
]
}
],
cursor : {
type : "XYCursor",
behavior : "zoomY"
},
colors : {
saturation : 0.4 // does not affect colors?
}
};
var chart = am4core.createFromConfig(config, "chartdiv", am4charts.XYChart);
chart.data = [{
"country": "[UAS]STATES",
"visits": 3025
}, {
"country": "China",
"visits": 1882
},{
"country": "Russia",
"visits": 580
}, {
"country": "South Korea",
"visits": 443
}, {
"country": "Canada",
"visits": 441}]
Brackets in amcharts are treated as reference to data.
Basically, it goes like this: whenever amCharts 4 displays a text, it passes it via text processor we call Text formatter. During the process anything contained within curly brackets { ... } is treated as a reference to some data value and is replaced with relative data. Similarly everything that goes within square brackets [ ... ] is treated as text formatting options, and again is not displayed but rather parsed for text styling instructions.
To solve your issue you need to escape brackets, like so:
country: "[[UAS]]STATES",
Take a look in Docs:
https://www.amcharts.com/docs/v4/concepts/formatters/formatting-strings/#Escaping

Value for field not found - AppSync AWS

I'm currently using AppSync to query against a GSI. I've been able to successfully use this block of code in a Pipeline Resolver function, but I don't know why it is not working when I try to use it in a traditional resolver.
I'm currently getting a mapping template error:
{
"data": {
"units": null
},
"errors": [
{
"path": [
"units"
],
"data": null,
"errorType": "MappingTemplate",
"errorInfo": null,
"locations": [
{
"line": 2,
"column": 3,
"sourceName": null
}
],
"message": "Value for field '$[version]' not found."
}
]
}
I tried searching in the AWS docs but adding "version" to the GraphQL type didn't work.
I also tried this (even though I'm not using S3)
AppSync S3Object retrieval
And the docs:
https://docs.aws.amazon.com/appsync/latest/devguide/troubleshooting-and-common-mistakes.html#mapping-template-errors
Here's the request mapping template:
#set($arg=$context.args)
{
"operation": "Query",
"index" : "userPK-userSK-index",
"query": {
"expression": "userPK = :pk and begins_with(userSK, :sk)",
"expressionValues": {
":pk": {"S": "tenant:${arg.tenantId}" },
":sk": {"S": "school-year:${arg.schoolYear}:grades:${arg.gradeId}:subject:${arg.subjectId}:unit:"}
}
}
}
Here's the response mapping template:
$util.toJson($ctx.result.items)
Here is a snippet of the executed GraphQL:
query GetUnits{
units(tenantId: "5fc30406-346c-42e2-8083-fda33ab6000a"
schoolYear: "2019-2020"
gradeId: "c737e341-a0cb-4a16-95de-f3a092049e74"
subjectId: "d0306e25-422d-4628-8fcc-c354b67c932a") {
id
indicator {
id,
description
}
competency {
id,
description,
name
}
description,
name
}
}
Here is a snippet of the GraphQL schema:
type Unit {
id: ID!
competency: Competency
indicator: Indicator
name: String!
description: String
version: Int
}
type Competency {
id: ID
# grade: Grade
# subject: Subject
# schoolYear: String
name: String
description: String
}
type Indicator {
id: ID!
description: String
}
type Query {
units(
tenantId: String!
schoolYear: String!
gradeId: String!
subjectId: String!
): [Unit]
Here's a data example from the DynamoDB table:
Here's a screenshot from a successful query in the Console:
Note: I have created a GSI that maps the userPK and userSK as partition key and sort key respectively. I'm querying that Secondary Index. I've been able to query this successfully using the console.
The error shows you forgot version parameter. This is the query template (docs):
{
"version" : "2017-02-28",
"operation" : "Query",
"query" : {
"expression" : "some expression",
"expressionNames" : {
"#foo" : "foo"
},
"expressionValues" : {
":bar" : ... typed value
}
}
"index" : "fooIndex",
"nextToken" : "a pagination token",
"limit" : 10,
"scanIndexForward" : true,
"consistentRead" : false,
"select" : "ALL_ATTRIBUTES",
"filter" : {
...
}
}
and the version is required:
version
The template definition version. 2017-02-28 and 2018-05-29 are currently supported. This value is required.

Ember js to work with HATEOAS REST API

I have a REST endpoint "http://localhost:8080/customers" which I would like to hook to my Ember JS app.
App.Store = DS.Store.extend({
revision: 12,
adapter: DS.RESTAdapter.extend({
url: 'http://localhost:8080/customers'
})
});
REST Payload
{
"_links" : {
"search" : {
"href" : "http://localhost:8080/customers/search"
}
},
"_embedded" : {
"customers" : [ {
"id" : 2,
"firstName" : "Jim",
"lastName" : "Smith",
"_links" : {
"self" : {
"href" : "http://localhost:8080/customers/2"
}
}
}, {
"id" : 1,
"firstName" : "Jimmy",
"lastName" : "Jones",
"_links" : {
"self" : {
"href" : "http://localhost:8080/customers/1"
}
}
} ]
}
}
I keep on getting this error. This is my second week on Ember JS. To be honest this is a lot harder than I imagined. Not very easy to debug or understand.
Error while loading route:
TypeError: undefined is not a function
at App.CustomersRoute.Ember.Route.extend.model
Essentially you need to transform your data into this format using a custom serializer:
{
"customers" : [
{
"id" : 2,
"firstName" : "Jim",
"lastName" : "Smith"
}, {
"id" : 1,
"firstName" : "Jimmy",
"lastName" : "Jones"
}
]
}
You'll want to read https://github.com/emberjs/data/blob/master/TRANSITION.md which explains how to use extractSingle, extractArray, normalize, normalizeHash.
You're particular example looks close to the api's example:
http://emberjs.com/api/data/classes/DS.RESTSerializer.html#method_extractArray
App.CustomerSerializer = DS.ActiveModelSerializer.extend({
extractArray: function(store, type, payload) {
// do your own implementation and return that, or modify it slightly
// and do the default implementation
return this._super(store, type, payload);
},
});

Sencha touch 2. Text doesn't obey the flex parameter in list item

I have defined this Ext.dataview.component.ListItem which renders some data from store into a list, but I cannot make the first text item to obey the flex rule and it's really annoying. It doesn't obey absolute width either. I have read all the documentation, but cannot figure this out by my self.
Ext.define('MyProgram.view.DataItem', {
extend : 'Ext.dataview.component.ListItem',
xtype : 'basic-dataitem',
requires : [
'Ext.Button',
'Ext.Component',
'Ext.layout.HBox',
'Ext.field.Checkbox'
],
config : {
text : {
flex : 1//This text doesn't take one out of two space in my list item
},
moreText : {
flex : 1//This text takes one out of one space???
},
dataMap :{
getText : {
setHtml : 'text'
},
getMoreText : {
setHtml : 'moreText'
}
},
layout : {
//I want texts to obey hbox layout
type : 'hbox',
align: 'center'
}
}
});
And here is the code for my Ext.dataview.List which uses the previously introduced list item MyProgram.view.DataItem:
Ext.define('MyProgram.view.Main', {
extend : 'Ext.dataview.List',
xtype : 'main',
id: 'MainList',
requires : [
'Ext.TitleBar',
'Ext.dataview.List',
'Ext.data.Store',
'Ext.plugin.PullRefresh',
'Ext.plugin.ListPaging',
'MyProgram.view.DataItem'
],
config : {
store : 'TodoItems',
useSimpleItems : false,
defaultType : 'basic-dataitem',
plugins : [
{
xclass : 'Ext.plugin.PullRefresh',
pullText : 'Pull down to refresh!'//Valid
//pullRefreshText : 'Pull down to refresh!'//Deprecated
},
{
xclass : 'Ext.plugin.ListPaging',
autoPaging : true
}
],
scrollable : {
direction : 'vertical',
directionLock : true
},
items : [
{
docked : 'top',
xtype : 'titlebar',
title : 'List using list items'
}
]
}
});
Looks like I want to disable the default itemTpl, so I can prevent sencha from adding raw htlm before my containers. I set my itemTpl in my list view to '' so it won't use the default '{text}' template for my model which ruins my styling.

What is the format expected by a find(id) request?

My backend replies to find all requests:
User.find();
Like this
{ 'users' : [ user1_obj, user2_obj ] }
Ember-data is happy about it. Now if I do a simple single object find:
User.find('user1');
I have tried configuring the backend to return any of the following:
user1
{ 'user1' : user1_obj }
{ 'user' : { 'user1' : user1_obj } }
{ 'user' : user1_obj }
But none of those are working. What should I return from the backend in reply to find("obj-id") requests? According to the documentation about JSON ROOT, the right format looks like:
{ 'user' : user1_obj }
Ember does not complain about it, but the Ember Objects processed have a very strange structure, like this:
As you can see, _reference.record is referring to the top record. Also (not shown here) _data field is empty.
What could be causing that strange nesting?
EDIT
As linked by mavilein in his answer, the JSON API suggests using a different format for singular resources:
{ 'users' : [user1_obj] }
That means, the same format as for plural resources. Not sure if Ember will swallow that, I'll check now.
Following this specification, i would suspect the following:
{
'users' : [{
"id": "1",
"name" : "John Doe"
},{
"id": "2",
"name" : "Jane Doe"
}]
}
For singular resources the specification says:
Singular resources are represented as JSON objects. However, they are
still wrapped inside an array:
{
'users' : [{
"id": "1",
"name" : "John Doe"
}]
}
Using User.find() will expect the rootKey pluralized and in your content an array of elements, the response format is the following json:
{
users: [
{ id: 1, name: 'Kris' },
{ id: 2, name: 'Luke' },
{ id: 3, name: 'Formerly Alex' }
]
}
And with User.find(1) the rootKey in singular, and just one object:
{
user: {
id: 1, name: 'Kris'
}
}
Here a demo showing this working