xbenjii / Prestan

PrestaShop Node.js API Library [UNMAINTAINED]
MIT License
20 stars 7 forks source link

prestashop.API_entry.entry_name is an object when 1 entry, array when multiple entries #6

Open sproit opened 8 years ago

sproit commented 8 years ago

Hi, sorry to bother you again :)

My use case applies to get('customers') but it is probably applicable to most calls. When there is just one entry to be returned by get('customers'), it is returned as follows:

{ prestashop: { '$': { 'xmlns:xlink': 'http://www.w3.org/1999/xlink' }, customers: { customer: { '$': { id: '4', 'xlink:href': 'http://shop0/api/customers/4' } } } } }

customer has object properties in this case.

When there are multiple entries, the format is the following: { prestashop: { '$': { 'xmlns:xlink': 'http://www.w3.org/1999/xlink' }, customers: { customer: [ { '$': [Object] }, { '$': [Object] } ] } } }

customer is an array in this case.

I did some minor digging and it seems that the explicitArray option of xml2js influences this behaviour. I think the interface would be stable (predictable object structure) when setting explicitArray to true, however the result is then slightly more cluttered:

{ prestashop: { '$': { 'xmlns:xlink': 'http://www.w3.org/1999/xlink' }, customers:[ { customer: [ [Object] ] } ] } }

My current javascript knowledge is not good enough to declutter this in a properly, otherwise I would have proposed something.

sproit commented 8 years ago

A first and very basic attempt to make the return values a bit simpler with explicitArray : true

var prestaGet = function(itemName, callback) {
    prestan.get(itemName).then(function(response) {
        var data = null;
        try {
            data = response.prestashop[itemName][0];
            return callback(null, data);
        } catch(err) {
            return callback(err, null);
        }
    });
};