Bienvenue sur PostGIS.fr

Bienvenue sur PostGIS.fr , le site de la communauté des utilisateurs francophones de PostGIS.

PostGIS ajoute le support d'objets géographique à la base de données PostgreSQL. En effet, PostGIS "spatialise" le serverur PostgreSQL, ce qui permet de l'utiliser comme une base de données SIG.

Maintenu à jour, en fonction de nos disponibilités et des diverses sorties des outils que nous testons, nous vous proposons l'ensemble de nos travaux publiés en langue française.

source: trunk/workshop-routing-foss4g/web/ext/src/data/JsonReader.js @ 79

Revision 76, 14.2 KB checked in by djay, 13 years ago (diff)

Ajout du répertoire web

  • Property svn:executable set to *
Line 
1/*!
2 * Ext JS Library 3.4.0
3 * Copyright(c) 2006-2011 Sencha Inc.
4 * licensing@sencha.com
5 * http://www.sencha.com/license
6 */
7/**
8 * @class Ext.data.JsonReader
9 * @extends Ext.data.DataReader
10 * <p>Data reader class to create an Array of {@link Ext.data.Record} objects
11 * from a JSON packet based on mappings in a provided {@link Ext.data.Record}
12 * constructor.</p>
13 * <p>Example code:</p>
14 * <pre><code>
15var myReader = new Ext.data.JsonReader({
16    // metadata configuration options:
17    {@link #idProperty}: 'id'
18    {@link #root}: 'rows',
19    {@link #totalProperty}: 'results',
20    {@link Ext.data.DataReader#messageProperty}: "msg"  // The element within the response that provides a user-feedback message (optional)
21
22    // the fields config option will internally create an {@link Ext.data.Record}
23    // constructor that provides mapping for reading the record data objects
24    {@link Ext.data.DataReader#fields fields}: [
25        // map Record&#39;s 'firstname' field to data object&#39;s key of same name
26        {name: 'name', mapping: 'firstname'},
27        // map Record&#39;s 'job' field to data object&#39;s 'occupation' key
28        {name: 'job', mapping: 'occupation'}
29    ]
30});
31</code></pre>
32 * <p>This would consume a JSON data object of the form:</p><pre><code>
33{
34    results: 2000, // Reader&#39;s configured {@link #totalProperty}
35    rows: [        // Reader&#39;s configured {@link #root}
36        // record data objects:
37        { {@link #idProperty id}: 1, firstname: 'Bill', occupation: 'Gardener' },
38        { {@link #idProperty id}: 2, firstname: 'Ben' , occupation: 'Horticulturalist' },
39        ...
40    ]
41}
42</code></pre>
43 * <p><b><u>Automatic configuration using metaData</u></b></p>
44 * <p>It is possible to change a JsonReader's metadata at any time by including
45 * a <b><tt>metaData</tt></b> property in the JSON data object. If the JSON data
46 * object has a <b><tt>metaData</tt></b> property, a {@link Ext.data.Store Store}
47 * object using this Reader will reconfigure itself to use the newly provided
48 * field definition and fire its {@link Ext.data.Store#metachange metachange}
49 * event. The metachange event handler may interrogate the <b><tt>metaData</tt></b>
50 * property to perform any configuration required.</p>
51 * <p>Note that reconfiguring a Store potentially invalidates objects which may
52 * refer to Fields or Records which no longer exist.</p>
53 * <p>To use this facility you would create the JsonReader like this:</p><pre><code>
54var myReader = new Ext.data.JsonReader();
55</code></pre>
56 * <p>The first data packet from the server would configure the reader by
57 * containing a <b><tt>metaData</tt></b> property <b>and</b> the data. For
58 * example, the JSON data object might take the form:</p><pre><code>
59{
60    metaData: {
61        "{@link #idProperty}": "id",
62        "{@link #root}": "rows",
63        "{@link #totalProperty}": "results"
64        "{@link #successProperty}": "success",
65        "{@link Ext.data.DataReader#fields fields}": [
66            {"name": "name"},
67            {"name": "job", "mapping": "occupation"}
68        ],
69        // used by store to set its sortInfo
70        "sortInfo":{
71           "field": "name",
72           "direction": "ASC"
73        },
74        // {@link Ext.PagingToolbar paging data} (if applicable)
75        "start": 0,
76        "limit": 2,
77        // custom property
78        "foo": "bar"
79    },
80    // Reader&#39;s configured {@link #successProperty}
81    "success": true,
82    // Reader&#39;s configured {@link #totalProperty}
83    "results": 2000,
84    // Reader&#39;s configured {@link #root}
85    // (this data simulates 2 results {@link Ext.PagingToolbar per page})
86    "rows": [ // <b>*Note:</b> this must be an Array
87        { "id": 1, "name": "Bill", "occupation": "Gardener" },
88        { "id": 2, "name":  "Ben", "occupation": "Horticulturalist" }
89    ]
90}
91 * </code></pre>
92 * <p>The <b><tt>metaData</tt></b> property in the JSON data object should contain:</p>
93 * <div class="mdetail-params"><ul>
94 * <li>any of the configuration options for this class</li>
95 * <li>a <b><tt>{@link Ext.data.Record#fields fields}</tt></b> property which
96 * the JsonReader will use as an argument to the
97 * {@link Ext.data.Record#create data Record create method} in order to
98 * configure the layout of the Records it will produce.</li>
99 * <li>a <b><tt>{@link Ext.data.Store#sortInfo sortInfo}</tt></b> property
100 * which the JsonReader will use to set the {@link Ext.data.Store}'s
101 * {@link Ext.data.Store#sortInfo sortInfo} property</li>
102 * <li>any custom properties needed</li>
103 * </ul></div>
104 *
105 * @constructor
106 * Create a new JsonReader
107 * @param {Object} meta Metadata configuration options.
108 * @param {Array/Object} recordType
109 * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
110 * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
111 * constructor created from {@link Ext.data.Record#create}.</p>
112 */
113Ext.data.JsonReader = function(meta, recordType){
114    meta = meta || {};
115    /**
116     * @cfg {String} idProperty [id] Name of the property within a row object
117     * that contains a record identifier value.  Defaults to <tt>id</tt>
118     */
119    /**
120     * @cfg {String} successProperty [success] Name of the property from which to
121     * retrieve the success attribute. Defaults to <tt>success</tt>.  See
122     * {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
123     * for additional information.
124     */
125    /**
126     * @cfg {String} totalProperty [total] Name of the property from which to
127     * retrieve the total number of records in the dataset. This is only needed
128     * if the whole dataset is not passed in one go, but is being paged from
129     * the remote server.  Defaults to <tt>total</tt>.
130     */
131    /**
132     * @cfg {String} root [undefined] <b>Required</b>.  The name of the property
133     * which contains the Array of row objects.  Defaults to <tt>undefined</tt>.
134     * An exception will be thrown if the root property is undefined. The data
135     * packet value for this property should be an empty array to clear the data
136     * or show no data.
137     */
138    Ext.applyIf(meta, {
139        idProperty: 'id',
140        successProperty: 'success',
141        totalProperty: 'total'
142    });
143
144    Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields);
145};
146Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, {
147    /**
148     * This JsonReader's metadata as passed to the constructor, or as passed in
149     * the last data packet's <b><tt>metaData</tt></b> property.
150     * @type Mixed
151     * @property meta
152     */
153    /**
154     * This method is only used by a DataProxy which has retrieved data from a remote server.
155     * @param {Object} response The XHR object which contains the JSON data in its responseText.
156     * @return {Object} data A data block which is used by an Ext.data.Store object as
157     * a cache of Ext.data.Records.
158     */
159    read : function(response){
160        var json = response.responseText;
161        var o = Ext.decode(json);
162        if(!o) {
163            throw {message: 'JsonReader.read: Json object not found'};
164        }
165        return this.readRecords(o);
166    },
167
168    /*
169     * TODO: refactor code between JsonReader#readRecords, #readResponse into 1 method.
170     * there's ugly duplication going on due to maintaining backwards compat. with 2.0.  It's time to do this.
171     */
172    /**
173     * Decode a JSON response from server.
174     * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
175     * @param {Object} response The XHR object returned through an Ajax server request.
176     * @return {Response} A {@link Ext.data.Response Response} object containing the data response, and also status information.
177     */
178    readResponse : function(action, response) {
179        var o = (response.responseText !== undefined) ? Ext.decode(response.responseText) : response;
180        if(!o) {
181            throw new Ext.data.JsonReader.Error('response');
182        }
183
184        var root = this.getRoot(o),
185            success = this.getSuccess(o);
186        if (success && action === Ext.data.Api.actions.create) {
187            var def = Ext.isDefined(root);
188            if (def && Ext.isEmpty(root)) {
189                throw new Ext.data.JsonReader.Error('root-empty', this.meta.root);
190            }
191            else if (!def) {
192                throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
193            }
194        }
195
196        // instantiate response object
197        var res = new Ext.data.Response({
198            action: action,
199            success: success,
200            data: (root) ? this.extractData(root, false) : [],
201            message: this.getMessage(o),
202            raw: o
203        });
204
205        // blow up if no successProperty
206        if (Ext.isEmpty(res.success)) {
207            throw new Ext.data.JsonReader.Error('successProperty-response', this.meta.successProperty);
208        }
209        return res;
210    },
211
212    /**
213     * Create a data block containing Ext.data.Records from a JSON object.
214     * @param {Object} o An object which contains an Array of row objects in the property specified
215     * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
216     * which contains the total size of the dataset.
217     * @return {Object} data A data block which is used by an Ext.data.Store object as
218     * a cache of Ext.data.Records.
219     */
220    readRecords : function(o){
221        /**
222         * After any data loads, the raw JSON data is available for further custom processing.  If no data is
223         * loaded or there is a load exception this property will be undefined.
224         * @type Object
225         */
226        this.jsonData = o;
227        if(o.metaData){
228            this.onMetaChange(o.metaData);
229        }
230        var s = this.meta, Record = this.recordType,
231            f = Record.prototype.fields, fi = f.items, fl = f.length, v;
232
233        var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
234        if(s.totalProperty){
235            v = parseInt(this.getTotal(o), 10);
236            if(!isNaN(v)){
237                totalRecords = v;
238            }
239        }
240        if(s.successProperty){
241            v = this.getSuccess(o);
242            if(v === false || v === 'false'){
243                success = false;
244            }
245        }
246
247        // TODO return Ext.data.Response instance instead.  @see #readResponse
248        return {
249            success : success,
250            records : this.extractData(root, true), // <-- true to return [Ext.data.Record]
251            totalRecords : totalRecords
252        };
253    },
254
255    // private
256    buildExtractors : function() {
257        if(this.ef){
258            return;
259        }
260        var s = this.meta, Record = this.recordType,
261            f = Record.prototype.fields, fi = f.items, fl = f.length;
262
263        if(s.totalProperty) {
264            this.getTotal = this.createAccessor(s.totalProperty);
265        }
266        if(s.successProperty) {
267            this.getSuccess = this.createAccessor(s.successProperty);
268        }
269        if (s.messageProperty) {
270            this.getMessage = this.createAccessor(s.messageProperty);
271        }
272        this.getRoot = s.root ? this.createAccessor(s.root) : function(p){return p;};
273        if (s.id || s.idProperty) {
274            var g = this.createAccessor(s.id || s.idProperty);
275            this.getId = function(rec) {
276                var r = g(rec);
277                return (r === undefined || r === '') ? null : r;
278            };
279        } else {
280            this.getId = function(){return null;};
281        }
282        var ef = [];
283        for(var i = 0; i < fl; i++){
284            f = fi[i];
285            var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
286            ef.push(this.createAccessor(map));
287        }
288        this.ef = ef;
289    },
290
291    /**
292     * @ignore
293     * TODO This isn't used anywhere??  Don't we want to use this where possible instead of complex #createAccessor?
294     */
295    simpleAccess : function(obj, subsc) {
296        return obj[subsc];
297    },
298
299    /**
300     * @ignore
301     */
302    createAccessor : function(){
303        var re = /[\[\.]/;
304        return function(expr) {
305            if(Ext.isEmpty(expr)){
306                return Ext.emptyFn;
307            }
308            if(Ext.isFunction(expr)){
309                return expr;
310            }
311            var i = String(expr).search(re);
312            if(i >= 0){
313                return new Function('obj', 'return obj' + (i > 0 ? '.' : '') + expr);
314            }
315            return function(obj){
316                return obj[expr];
317            };
318
319        };
320    }(),
321
322    /**
323     * type-casts a single row of raw-data from server
324     * @param {Object} data
325     * @param {Array} items
326     * @param {Integer} len
327     * @private
328     */
329    extractValues : function(data, items, len) {
330        var f, values = {};
331        for(var j = 0; j < len; j++){
332            f = items[j];
333            var v = this.ef[j](data);
334            values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
335        }
336        return values;
337    }
338});
339
340/**
341 * @class Ext.data.JsonReader.Error
342 * Error class for JsonReader
343 */
344Ext.data.JsonReader.Error = Ext.extend(Ext.Error, {
345    constructor : function(message, arg) {
346        this.arg = arg;
347        Ext.Error.call(this, message);
348    },
349    name : 'Ext.data.JsonReader'
350});
351Ext.apply(Ext.data.JsonReader.Error.prototype, {
352    lang: {
353        'response': 'An error occurred while json-decoding your server response',
354        'successProperty-response': 'Could not locate your "successProperty" in your server response.  Please review your JsonReader config to ensure the config-property "successProperty" matches the property in your server-response.  See the JsonReader docs.',
355        'root-undefined-config': 'Your JsonReader was configured without a "root" property.  Please review your JsonReader config and make sure to define the root property.  See the JsonReader docs.',
356        'idProperty-undefined' : 'Your JsonReader was configured without an "idProperty"  Please review your JsonReader configuration and ensure the "idProperty" is set (e.g.: "id").  See the JsonReader docs.',
357        'root-empty': 'Data was expected to be returned by the server in the "root" property of the response.  Please review your JsonReader configuration to ensure the "root" property matches that returned in the server-response.  See JsonReader docs.'
358    }
359});
Note: See TracBrowser for help on using the repository browser.