Skip to content

Instantly share code, notes, and snippets.

@heapwolf
Created February 1, 2021 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heapwolf/08616ec359836dc333a00956d747a25c to your computer and use it in GitHub Desktop.
Save heapwolf/08616ec359836dc333a00956d747a25c to your computer and use it in GitHub Desktop.
iterify

Convert aws api calls that require continuation tokens into simple iterators.

const iterify = ({ client, method, params, hint, token }) => {
  let finished = false
  const values = []

  return {
    [Symbol.asyncIterator] () {
      return this
    },
    next: async () => {
      if (values.length) {
        return { value: { data: values.shift() } }
      }

      if (finished) {
        return { done: true }
      }

      let res = null

      try {
        res = await client[method](params).promise()
      } catch (err) {
        return { value: { err } }
      }

      if (res.Contents && res.Contents.length) {
        values.push(...res.Contents)
      }

      if (res[hint]) {
        params[token] = res[token]
      } else {
        finished = true
      }

      const data = values.shift()

      if (typeof data === 'undefined') {
        return { done: true }
      }

      return { value: { data } }
    }
  }
}
const itr = itrify({
  client: require('aws-sdk/clients/s3'),
  method: 'listObjectsV2',
  hint: 'NextContinuationToken',
  token: 'ContinuationToken'
})

for await (const { err, data } of itr) {
  if (err) ...
  console.log(data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment