JSON different from Extjs 4 model? code for catching invalid or missing field names

I have a working grid that is recieving data as json, where the json is matching the model. However in the real world, things aren't always this clean and controlled. We may end up with fields missing or entries with the wrong field name, or even extra fields that don't exist in the model. So if we want the process halted if the json does not match the model how can catch it?

I extended the Extjs reader class, and then implemented to over-ridden methods from the original class, and sent errors to the console and replaced missing fields with a message.

Ext.define('App.Reader', {
    extend: 'Ext.data.reader.Json',

    extractData: function(root) {
        var me = this,
            values  = [],
            records = [],
            Model   = me.model,
            i       = 0,
            length  = root.length,
            idProp  = me.getIdProperty(),
            node, id, record;

        if (!root.length && Ext.isObject(root)) {
            root = [root];
            length = 1;
        }

        for (; i < length; i++) {
            node   = root[i];
            values = me.extractValues(node);
            id     = me.getId(node);

            record = new Model(values, id, node);
            records.push(record);

            if (me.implicitIncludes) {
                me.readAssociated(record, node);
            }
            
        }

        return records;
    },

    extractValues: function(data) {
        var fields = this.getFields(),
            i      = 0,
            length = fields.length,
            output = {},
            field, value;

        for (; i < length; i++) {
            field = fields[i];
            value = this.extractorFunctions[i](data);

            if(value === undefined)
            {
                Ext.iterate(fields, function(key, val) {
                    if (data[key] === undefined & i==val) {
                        console.log( "Model field <" + key.name + "> does not exist in data/node.");
                        value = "INVALID OR MISSING FIELD NAME";
                        var p = 0;
                        for(var prop in data) {
                            if(p==i){
                                if(data.hasOwnProperty(prop))console.log("Instead of <" + key.name + "> we have <" + prop + "> with value <" + data[prop]+ ">");
                            }
                            p++;
                        }
                    }
                }, this);
            }

            output[field.name] = value;
        }

        return output;
    }

});

var myReader = new App.Reader({
    type:'json'
});



Now when defining a proxy for a store or model we can use the instance of the reader above.

Comments

Popular posts from this blog

Getting Started: Quick Setup for GXT 3 (includes reset.css link how to)

How to setup GXT 3 examples, samples and demos

ExtJs4 : Dynamically Add Columns