feat: enable loading all the cryptokitties assets with recursion

This commit is contained in:
Jonathan Rainville 2020-09-25 11:53:25 -04:00 committed by Iuri Matias
parent 9acb6609ab
commit 51e1ba6f38
1 changed files with 40 additions and 30 deletions

View File

@ -59,19 +59,17 @@ proc tokensOfOwnerByIndex(contract: Contract, address: Address): seq[int] =
result.add(token) result.add(token)
index = index + 1 index = index + 1
proc getCryptoKitties*(address: Address): string = proc getCryptoKittiesBatch*(address: Address, offset: int = 0): seq[Collectible] =
var cryptokitties: seq[Collectible] var cryptokitties: seq[Collectible]
cryptokitties = @[] cryptokitties = @[]
try:
# TODO handle testnet -- does this API exist in testnet?? # TODO handle testnet -- does this API exist in testnet??
# TODO handle offset (recursive method?) let url: string = fmt"https://api.cryptokitties.co/kitties?limit=20&offset={$offset}&owner_wallet_address={$address}&parents=false"
# Crypto kitties has a limit of 20
let url: string = fmt"https://api.cryptokitties.co/kitties?limit=20&offset=0&owner_wallet_address={$address}&parents=false"
let client = newHttpClient() let client = newHttpClient()
client.headers = newHttpHeaders({ "Content-Type": "application/json" }) client.headers = newHttpHeaders({ "Content-Type": "application/json" })
let response = client.request(url) let response = client.request(url)
let kitties = parseJson(response.body)["kitties"] let responseBody = parseJson(response.body)
let kitties = responseBody["kitties"]
for kitty in kitties: for kitty in kitties:
try: try:
var id = kitty["id"] var id = kitty["id"]
@ -90,12 +88,24 @@ proc getCryptoKitties*(address: Address): string =
externalUrl: "")) externalUrl: ""))
except Exception as e2: except Exception as e2:
error "Error with this individual cat", msg = e2.msg, cat = kitty error "Error with this individual cat", msg = e2.msg, cat = kitty
let limit = responseBody["limit"].getInt
let total = responseBody["total"].getInt
if (limit * (offset + 1) < total):
# Call the API again with oofset + 1
let nextBatch = getCryptoKittiesBatch(address, offset + 1)
return concat(cryptokitties, nextBatch)
return cryptokitties
proc getCryptoKitties*(address: Address): string =
try:
let cryptokitties = getCryptoKittiesBatch(address, 0)
return $(%*cryptokitties)
except Exception as e: except Exception as e:
error "Error getting Cryptokitties", msg = e.msg error "Error getting Cryptokitties", msg = e.msg
return e.msg return e.msg
return $(%*cryptokitties)
proc getCryptoKitties*(address: string): string = proc getCryptoKitties*(address: string): string =
let eth_address = parseAddress(address) let eth_address = parseAddress(address)
result = getCryptoKitties(eth_address) result = getCryptoKitties(eth_address)