0

I am trying to compile a list of all customers using the Stripe Node API. I need to make continual fetches 100 customers at a time. I believe that I need to use a Promise within the API call to use async await, but I can't for the life of me figure out where to put it. Hoping to make this gist public use and I want to get it right, thanks.

getAllCustomers()

function getMoreCustomers(customers, offset, moreCustomers, limit) {
  if (moreCustomers) {
    stripe.customers.list({limit, offset},
      (err, res) => {
        offset += res.data.length
        moreCustomers = res.has_more
        customers.push(res.data)
        return getMoreCustomers(customers, offset, moreCustomers, limit)
      }
    )
  }
  return customers
}

async function getAllCustomers() {
  const customers = await getMoreCustomers([], 0, true, 100)
  const content = JSON.stringify(customers)
  fs.writeFile("/data/stripe-customers.json", content, 'utf8', function (err) {
      if (err) {
          return console.log(err);
      }
      console.log("The file was saved!");
  });
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
user4815162342
  • 1,638
  • 2
  • 17
  • 23

2 Answers2

0

IF res in stripe.customers.list({limit, offset}).then(res => ...) is the same as res in the "callback" version of stripe.customers.list({limit, offset}, (err, res) - then you probably could rewrite your code like

const getMoreCustomers = limit => {
    const getThem = offset => stripe.customers.list({limit, offset})
    .then(res => res.has_more ? 
        getThem(offset + res.data.length).then(result => res.data.concat(...result)) : 
        res.data
    );
    return getThem(0);
};

async function getAllCustomers() {
    const customers = await getMoreCustomers(100);
    const content = JSON.stringify(customers);
    fs.writeFile("/data/stripe-customers.json", content, 'utf8', function (err) {
        if (err) {
            return console.log(err);
        }
        console.log("The file was saved!");
    });
}
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
0

additional to Jaromanda X's answer, it seems there is no offset option to customers api, but starting_after https://stripe.com/docs/api/node#list_customers

So, getMoreCustomers may be fixed like

const getMoreCustomers = starting_after => {
  const getThem = starting_after => stripe.customers.list({limit: 100, starting_after: starting_after})
  .then(res => res.has_more ? 
      getThem(res.data[res.data.length - 1]).then(result => res.data.concat(...result)) : 
      res.data
  );
  return getThem(starting_after);
};

async function getAllCustomers() {
  const customers = await getMoreCustomers(null);
  const content = JSON.stringify(customers);
  fs.writeFile("/data/stripe-customers.json", content, 'utf8', function (err) {
    if (err) {
      return console.log(err);
    }
    console.log("The file was saved!");
  });
}
zakuni
  • 51
  • 12