chiefbiiko / dynamodb

deno <3 dynamodb
MIT License
25 stars 11 forks source link

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

Open hayd opened 4 years ago

hayd commented 4 years ago

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>> ?

chiefbiiko commented 4 years ago

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

chiefbiiko commented 4 years ago

@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 */
}
hayd commented 4 years ago

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 commented 4 years ago

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...)

wperron commented 4 years ago

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?