parent
70b00ed17a
commit
989ee117b5
@ -0,0 +1,50 @@ |
||||
defmodule Explorer.Resource do |
||||
|
||||
@moduledoc "Looks up and fetches resource based on its handle (either an id or hash)" |
||||
|
||||
import Ecto.Query, only: [from: 2] |
||||
|
||||
alias Explorer.Block |
||||
alias Explorer.BlockForm |
||||
|
||||
alias Explorer.Address |
||||
alias Explorer.Repo.NewRelic, as: Repo |
||||
alias Explorer.Transaction |
||||
|
||||
def lookup(hash) when byte_size(hash) > 42, do: fetch_transaction(hash) |
||||
|
||||
def lookup(hash) when byte_size(hash) == 42, do: fetch_address(hash) |
||||
|
||||
def lookup(number), do: fetch_block(number) |
||||
|
||||
def fetch_address(hash) do |
||||
query = from address in Address, |
||||
where: fragment("lower(?)", address.hash) == ^String.downcase(hash), |
||||
limit: 1 |
||||
|
||||
Repo.one(query) |
||||
end |
||||
|
||||
def fetch_transaction(hash) do |
||||
query = from transaction in Transaction, |
||||
where: fragment("lower(?)", transaction.hash) == ^String.downcase(hash), |
||||
limit: 1 |
||||
|
||||
Repo.one(query) |
||||
end |
||||
|
||||
def fetch_block(block_number) when is_bitstring(block_number) do |
||||
case Integer.parse(block_number) do |
||||
{number, ""} -> fetch_block(number) |
||||
_ -> nil |
||||
end |
||||
end |
||||
|
||||
def fetch_block(number) when is_integer(number) do |
||||
query = from b in Block, |
||||
where: b.number == ^number, |
||||
limit: 1 |
||||
|
||||
Repo.one(query) |
||||
end |
||||
end |
@ -0,0 +1,45 @@ |
||||
defmodule Explorer.ResourceTest do |
||||
use Explorer.DataCase |
||||
|
||||
alias Explorer.Resource |
||||
|
||||
describe "lookup/1" do |
||||
test "finds a block by block number with a valid block number" do |
||||
insert(:block, number: 37) |
||||
block = Resource.lookup("37") |
||||
|
||||
assert block.number == 37 |
||||
end |
||||
|
||||
test "finds a transaction by hash" do |
||||
transaction = insert(:transaction) |
||||
|
||||
resource = Resource.lookup(transaction.hash) |
||||
|
||||
assert transaction.hash == resource.hash |
||||
end |
||||
|
||||
test "finds an address by hash" do |
||||
address = insert(:address) |
||||
|
||||
resource = Resource.lookup(address.hash) |
||||
|
||||
assert address.hash == resource.hash |
||||
end |
||||
|
||||
test "returns nil when garbage is passed in" do |
||||
item = Resource.lookup("any ol' thing") |
||||
|
||||
assert is_nil(item) |
||||
end |
||||
|
||||
test "returns nil when it does not find a match" do |
||||
transaction_hash = String.pad_trailing("0xnonsense", 43, "0") |
||||
address_hash = String.pad_trailing("0xbaddress", 42, "0") |
||||
|
||||
assert is_nil(Resource.lookup("38999")) |
||||
assert is_nil(Resource.lookup(transaction_hash)) |
||||
assert is_nil(Resource.lookup(address_hash)) |
||||
end |
||||
end |
||||
end |
Loading…
Reference in new issue