christophergregory / shopify-node-api

OAuth2 Module for Shopify API
MIT License
216 stars 74 forks source link

Send data from inner-most API call to another to send response back to client? #71

Closed patrickbolle closed 7 years ago

patrickbolle commented 7 years ago

Hi there again... Sorry for making another issue.. This is more a logic problem on my side, but wondering if shopify-node-api has anything built in that could help me.

I'm trying to grab all customers + each customer's metafield. Shopify doesn't have an API that I could easily grab all at once with,so I need multiple calls sadly.

I'm using express + need to get my data from my innermost for loop API call, and send it to the outer API call so I can bundle it all up and send it as a response to the client. Here's my code

router.get('/customers', (req, res) => {
    Shopify.get('/admin/customers.json', function(err, data, headers){
        for (var i = 0; i < data.customers.length; i++) {
            Shopify.get('/admin/metafields.json?metafield[owner_id]=' + data.customers[i].id + '&metafield[owner_resource]=customer', function(err, data, headers){ 
                for (var i = 0; i < data.metafields.length; i++) {
                    console.log(data.metafields[i]);
                    //THIS WORKS!!!
                    // return callback(data.metafields[i]);
                }
            });
        }
    });
});

Any helpers here? I'm trying to just show a list of all customers with ther metafields.Anyone have a better solution?

christophergregory commented 7 years ago

Hi Patrick,

While this isn't really the place for this (all issues should be specific to this module, your question is more javascript specific) I can give you a few a pointers.

First of all, your code is suffering from callback hell :) Getting that squared away first will make it easier to reason about your code.

Second of all, what you are trying to accomplish really shouldn't be done within a request as it can take a long time and will likely frustrate your customers or worse. You should perform this in a background job and save the results to a database. That way you can quickly retrieve the information and send it to the customer that is requesting it.

To answer your question though, you will need to store your results in a variable as they are received and then send them in the response once all requests have finished. As you can see, this can be a bit tricky because you have to deal with the async flow of node.js yourself (one of the downsides of Node in my opinion).

There are several options:

Research and try some of these options yourself and if you are still having issues let me know and I can help you further. In my opinion it's always best to let you go through the pain of figuring it out on your own first :)

patrickbolle commented 7 years ago

Cheers Chris. Thanks a bunch for your help, will look into that!!