SSPkrolik / nimongo

Pure Nim lang MongoDB driver
http://sspkrolik.github.io/nimongo
MIT License
101 stars 20 forks source link

remove all the code duplication between async and sync #63

Open timotheecour opened 5 years ago

timotheecour commented 5 years ago

note

this is irrelevant if sync is deprecated, see https://github.com/SSPkrolik/nimongo/issues/61

body

the following is just an example take from codebase; there are other such examples.

The code duplication could be removed using either a macro, or template ; the synchronous version could just call the async one and call waitFor on it (maybe)

proc listDatabases*(sm: Mongo): seq[string] =
  ## Return list of databases on the server
  let response = sm["admin"]["$cmd"].makeQuery(%*{"listDatabases": 1}).one()
  result = @[]
  if response.isReplyOk:
    for db in response["databases"].items():
      result.add(db["name"].toString())

proc listDatabases*(am: AsyncMongo): Future[seq[string]] {.async.} =
  ## Return list of databases on the server via async client
  let response = await am["admin"]["$cmd"].makeQuery(%*{"listDatabases": 1}).one()
  result = @[]
  if response.isReplyOk:
    for db in response["databases"].items():
      result.add(db["name"].toString())

this could become (untested):

type AnyMongo = AsyncMongo | Mongo
proc listDatabases*(am: AnyMongo): MaybeFuture(seq[string]) {.async.} =
  ## Return list of databases on the server
  let response = maybeAwait am["admin"]["$cmd"].makeQuery(%*{"listDatabases": 1}).one()
  result = @[]
  if response.isReplyOk:
    for db in response["databases"].items():
      result.add(db["name"].toString())
yglukhov commented 5 years ago

Well iirc there's {.multisync.} we could potentially leverage to dry up the code. But my personal take on this is that in regards to networking sync (and multisync) is just harmful and should burn in hell.