dynamodb icon indicating copy to clipboard operation
dynamodb copied to clipboard

How to use Promise<Doc | AsyncIterableIterator<Doc>> ?

Open hayd opened this issue 5 years ago • 5 comments

Is there a better way to consume Promise<Doc | AsyncIterableIterator<Doc>>

What I was doing seems very hacky: https://github.com/hayd/deno-lambda/blob/1ec6178894eba338da24702845baef5c23dc8139/example/api/candidate.ts#L52-L59

Is there a way to use discriminated unions ?

Perhaps it'd be better if these always returned Promise<AsyncIterableIterator<Doc>> ?

hayd avatar Dec 08 '19 05:12 hayd

Yea I agree
Probly makes sense to have scan and query always return an async iterator

chiefbiiko avatar Dec 10 '19 08:12 chiefbiiko

@hayd sorry for the late late response

unfortunately, always returning an async iterator does not really make sense - the scan and query ops can return a single or multiple pages - details here

however, to answer your question I would test for the async iterator symbol:

if (result.hasOwnProperty(Symbol.asyncIterator)) {
  for await (const page of result) {/* handle page.Items */}
} else {
  /* handle result.Items */
}

chiefbiiko avatar Feb 24 '20 07:02 chiefbiiko

Will the above work with 0.34.0 / strict mode?

If the op returns single page couldn't you wrap it to make this case into an asyncIterator ?

I think it would be much nicer to do this in library code rather than user code... since almost always the handling of page.Items will be the same as result.Items.

hayd avatar Feb 24 '20 08:02 hayd

Something like the following could ensure it's always AsyncIterable<Doc>:

async function *toAsyncIterable(res: Doc | AsyncIterable<Doc>): AsyncIterable<Doc> {
  if (res.hasOwnProperty(Symbol.asyncIterator)) {
    // @ts-ignore
    for await (const r of res) {
      yield r
    }
  } else {
    yield res
  }
}

(not sure how to avoid the @ts-ignore...)

hayd avatar Mar 01 '20 02:03 hayd

Hey all, reviving this issue a bit; What I find myself missing when using this lib are the typings provided by the official lib, they're just very comprehensive and explicit. What do you feel about using those typings, or taking inspiration from them?

wperron avatar Oct 28 '20 11:10 wperron