viezel / napp.alloy.adapter.restapi

RestAPI Sync Adapter for Titanium Alloy Framework
197 stars 102 forks source link

complex objects as urlparams cause errors #14

Closed dknell closed 10 years ago

dknell commented 11 years ago

The following urlparams will cause and error because the encodeData function is only looking one level deep.

var project = Alloy.Collections.project;
project.fetch({
    urlparams: {
        fields: {title: 1, category: 1}
    },
    success: function (model, res) {
        Ti.API.info('Success');
    },
    error: function (model, res) {

    }
});

Writing your own object/array to URI query string converter seems like overkill for this adapter when there are other libraries that do this very well. While I can appreciate that this adapter has no dependencies, perhaps using a query string library would be beneficial to everyone. I added https://github.com/visionmedia/node-querystring to the adapter and it works great. Maybe we could use node-querystring ONLY if require can find it... and it could fall back to the encodeData function if not.

I could submit a patch if it's something you would be interested in.

viezel commented 11 years ago

Hi dbubs,

You are very welcome to do a PR. But I dont want two files. So if you wanna include node-querystring into the adapter, please go ahead and add it. Too me, it seems a bit overkill to get an entire library for such a small task. Maybe it would be easier just to extend my function to be multi level depth.

pelluch commented 10 years ago

Correct me if I'm wrong, but currently, the issue is the following line:

str.push(Ti.Network.encodeURIComponent(p) + "=" + Ti.Network.encodeURIComponent(obj[p]));

When obj[p] is an object, as dbubs mentions, this causes an error. However, if you wrap it around a JSON.stringify method call, then obj[p] is correctly encoded, regardless of whether it's an object or some value type, and whether there are more nested objects or not. The line would change to

str.push(Ti.Network.encodeURIComponent(p) + "=" + Ti.Network.encodeURIComponent(JSON.stringify(obj[p])));

This works fine after some simple testing, except when there's circular references involved. If you'd like, I can submit a PR involving either the simple (no circular references) or more complex case.

viezel commented 10 years ago

Hi @pelluch please do and following your complex sample so other can benefit from this feature. Please remember to bump up the version number and add a line in the readme. cheers!