Use without data layers
Hi,
I'm trying to fit the example from https://hexdocs.pm/ash/use-without-data-layers.html to call a web api,
defmodule Asher.Edge.FetchMyip do
use Ash.Resource.Preparation
def prepare(query, _, _) do
case Req.get("https://httpbin.org/ip") do
{:ok,
%Req.Response{
status: 200,
body: data
}} ->
Ash.DataLayer.Simple.set_data(query, data)
{:error, error} ->
Ash.Query.add_error(query, "doh #{inspect(error)}")
end
end
end
when trying to read i get
iex(21)> Ash.Query.for_read(Asher.Edge.Myip, :read) |> Asher.Edge.read!()
** (Ash.Error.Unknown) Unknown Error
Context: resolving data on fetch Asher.Edge.Myip.read
* Context: resolving data on fetch Asher.Edge.Myip.read
** (KeyError) key :__metadata__ not found in: %{"origin" => "80.208.68.43"}
(ash 2.14.12) lib/ash/resource.ex:267: Ash.Resource.set_metadata/2
.....
Anyone who can point me to a working example on how to consume a web api ?5 Replies
From the error message I'm guessing you need to turn your data into a resource before putting it into the Datalayer
If I'm not mistaken you can just use the resources create action to turn the data into a resource
Yep! Or you can do
%YourResource{foo: ....}
Thx, if i do it like this,
defmodule Asher.Edge.FetchMyip do
use Ash.Resource.Preparation
def prepare(query, _, _) do
case Req.get("https://httpbin.org/ip") do
{:ok,
%Req.Response{
status: 200,
body: data
}} ->
# data =
# Asher.Edge.Myip
# |> Ash.Changeset.for_create(:create, %{origin: data["origin"]})
# |> Asher.Edge.create!()
Ash.DataLayer.Simple.set_data(query, %Asher.Edge.Myip{origin: data["origin"]})
{:error, error} ->
Ash.Query.add_error(query, "doh #{inspect(error)}")
end
end
end
Ash.Query.for_read(Asher.Edge.Myip, :read) |> Asher.Edge.read!()
(Ash.Error.Unknown) Unknown Error
Context: resolving data on process Asher.Edge.Myip.read
* Context: resolving data on process Asher.Edge.Myip.read
(Protocol.UndefinedError) protocol Enumerable not implemented for #Asher.Edge.Myip<meta: #Ecto.Schema.Metadata<:built, "">, id: nil, origin: "80.208.68.43", aggregates: %{}, calculations: %{}, ...> of type Asher.Edge.Myip (a struct). This protocol is implemented for the following type(s): Date.Range, File.Stream, Fu
I will probably need to do some more readingYou also need to set it to a list
That did the trick, thank you !