Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extjs4 - is there a non json/xml writer for proxies?

Tags:

extjs

extjs4

I'm building some models to interact with an existing API from a previous project.

The API relies on standard POST methods to save the data.

I've configured a model and proxy up to the point where it does push the data onto the server but there only seems to be two writer types, json & xml.

proxy: {
        /* ... */
        reader: {
            type: 'json',
            root: 'results'
        },
        writer: {
            type: '???' // <-- can only see json or xml in the docs
        }
    }

Isn't there a standard POST writer that simply submits data in post fields?

I'm surprised that wouldn't be a standard writer type.

(Parsing the json format wouldn't be too hard to implement but that would mean updating a lot of the old api files.)

like image 513
Ben Avatar asked Sep 14 '11 13:09

Ben


2 Answers

Ok, I was able to create that writer quite easily by checking the existing writers' source code.

One thing those existing writers are able to do - and that may be why the dev team only implemented a json and xml version - is that they can push multiple records at once.

That could be implemented in POST but would be a bit more complicated.

This writer will work if you're trying to push a single model to an api using POST:

Ext.define('Ext.data.writer.SinglePost', {
    extend: 'Ext.data.writer.Writer',
    alternateClassName: 'Ext.data.SinglePostWriter',
    alias: 'writer.singlepost',

    writeRecords: function(request, data) {
        request.params = data[0];
        return request;
    }
});

and the use this for the writer in the proxy:

writer: {
            type: 'singlepost'
        }
like image 156
Ben Avatar answered Oct 12 '22 21:10

Ben


Based on Ben answer I've implemented my own writer that will collect all properties of all models into arrays. For example if you have model like with some fields:

fields:[
  {name:'id', type:'int'}
  {name:'name', type:'string'}
  {name:'age', type:'date'}
]

A request string will be

id=1&id=2&id=...&name=oleks&name=max&name=...&age=...

Code:

Ext.define('Ext.data.writer.SinglePost', {
    extend: 'Ext.data.writer.Writer',
    alternateClassName: 'Ext.data.SinglePostWriter',
    alias: 'writer.singlepost',
    writeRecords: function(request, data) {
        if(data && data[0]){
            var keys = [];
            for(var key in data[0]){
                keys.push(key);
            }
            for(var i=0;i<keys.length;i++){
                request.params[keys[i]] = [];
                for(var j=0;j<data.length;j++){
                request.params[keys[i]].push((data[j])[keys[i]]);
            }
        }
        }
        return request;
    }
});
like image 26
Oleksandr_DJ Avatar answered Oct 12 '22 21:10

Oleksandr_DJ