PDA

View Full Version : Scenario for getting JSON from a REST service into a Store/Model



jroets
4 Nov 2011, 12:37 PM
So I have a web service that returns a stock fund along with some price history. It's one endpoint; e.g. /Stocks/IBM. Let's say the json looks like this:



{
"symbol": "IBM",
"name": "International Business Machines",
"prices": [

{

"date": "10/1/2011",
"price": "145.34"

},
{

"date": "11/1/2011",
"price": "185.01"

}]
}


I'm confused by how I would set up my model(s) and store(s) in Sencha. Based on the documentation, it seems like I need two models: one for a "Stock", and one for "StockSnapshot", like this:



Ext.regModel('Stock', {
fields: [
{name: 'symbol', type: 'string'}
],
hasMany: {model: 'StockSnapshot', name: 'prices', foreignKey: 'fundId'}
});

Ext.regModel('StockSnapshot', {
fields: [
{name: 'date', type: 'date'},
{name: 'price', type: 'float'}
],
belongsTo: 'Stock'
}



But my data is coming from a single service call, and there is not "foreign key" in the prices collection.

How do I make this work?

mitchellsimoens
4 Nov 2011, 1:17 PM
Are you wanting to use associations? It's not required.

jroets
4 Nov 2011, 5:33 PM
How do I do this without associations. I think maybe I'm confused by the "fields" property on the Model. How can I assign a collection to a field? A "field" only seems to support types like 'int', 'float', 'date', etc. I don't see 'collection'. What am I not understanding?

mitchellsimoens
4 Nov 2011, 5:37 PM
Default is auto which means no converting will happen so if you pass in an array, it will be an array

jroets
7 Nov 2011, 9:42 AM
Ok. Very good. So I end up with a model definition that looks like this:



Ext.regModel('Stock', {
fields: [
{name: 'id', type: 'int'},
{name: 'symbol', type: 'string'},
{name: 'prices', type: 'auto'}
]
});


But if I do this, can you tell me how I can map the fields of the objects in my prices array into my model ? If I can't do this, then all of its fields are treated as strings. For example, assuming I have a stockStore loaded with some stocks:



var ibm = stockStore.findRecord('symbol', 'IBM');
var prices = ibm.get("prices");
prices.date.getTime();


That last line of code fails because prices.date is not a date, it is a string. I would expect I could set up the entire hierarchy of my model, including mapping and type definition.

Given that the data comes to me as I specified in my original post, how can I accomplish what I want?

Thank you for your help.

mitchellsimoens
7 Nov 2011, 11:24 AM
You can (via convert) or you can check to see if it is a date. If not, make it be a date:


var date = prices.date;

if (!Ext.isDate(date)) {
date = Date.parseDate(date, 'Y-m-d'); //change 'Y-m-d' to whatever format
}