bitwalker / timex_ecto

An adapter for using Timex DateTimes with Ecto
MIT License
162 stars 68 forks source link

Encode/Decode in JSON #62

Closed eppdot closed 7 years ago

eppdot commented 7 years ago

I am using Ecto only for schema and changeset. I store my values within redis as JSON blobs. But I am unable to decode the blob into a schema using Timex.Ecto.Time

defmodule Test.Value do
  use Ecto.Schema

  @derive {Poison.Encoder, except: [:__meta__]}
  @primary_key {:id, :binary_id, autogenerate: false}
  schema("latest") do
    field :timestamp, Timex.Ecto.DateTime
    field :value, :boolean
  end
end

In my (custom) Repo

  defp serialize(data) do
    data |> Poison.encode!
  end

  defp deserialize(model, data) do
    model.__struct__
    |> Ecto.Changeset.cast(Poison.decode!(data), model.__schema__(:fields))
    |> Ecto.Changeset.apply_changes()
  end

and I am getting timestamp: nil. For example:

 data = %{"id" => "feed:0", "timestamp" => "2017-05-22T13:05:32.771489Z", "value" => true}
 %Test.Value{} |> Ecto.Changeset.cast(data, [:timestamp, :id])
 #Ecto.Changeset<action: nil, changes: %{id: "feed:0"},
 errors: [timestamp: {"is invalid",
   [type: Timex.Ecto.Time, validation: :cast]}],
 data: #Alerting.Subscriptions.Value<>, valid?: false>
eppdot commented 7 years ago

Please close issue, I used Time where I should have used DateTime. Sorry for any inconvenience.