defmodule Manganese.SerializationKit.Structs.UnityAssetBundle do @moduledoc """ A Unity asset bundle. This module can be used as an Ecto type for de/serialization when interacting with the database. ## Deserialization *See `from_map/1`* ## Serialization *See `to_map/1`* ## Asset utilities *See `has_asset?/2`* """ alias Manganese.SerializationKit.Structs alias Manganese.SerializationKit.Enumerations @typedoc """ A Unity asset bundle. """ @type t :: %Structs.UnityAssetBundle{ name: String.t, assets: [ Structs.UnityAsset.t ] } @enforce_keys [ :name, :assets ] defstruct [ :name, :assets ] # Deserialization @doc """ Deserialize an asset bundle from a map. """ @spec from_map(t_external) :: t def from_map(%{ "name" => name, "assets" => assets } = map) do %Structs.UnityAssetBundle{ name: name, assets: assets |> Enum.map(&Structs.UnityAsset.from_map/1) } end # Serialization @type t_external :: map @doc """ Serialize an asset bundle to a map. """ @spec to_map(t) :: t_external def to_map(%Structs.UnityAssetBundle{ name: name, assets: assets }) do %{ "name" => name, "assets" => assets |> Enum.map(&Structs.UnityAsset.to_map/1) } end # Utilities @doc """ Check if an asset bundle has an asset with the specified path and asset type. """ @spec has_asset?(t, String.t, Enumerations.UnityAssetType.t | nil) :: boolean def has_asset?(%Structs.UnityAssetBundle{ assets: assets }, asset_path, asset_type \\ nil) do case Enum.find(assets, fn asset -> asset.path == asset_path end) do %_{ type: type } -> cond do not is_nil(asset_type) and type != asset_type -> false true -> true end _ -> false end end # Ecto type use Ecto.Type @doc """ The PostgreSQL type used to represent a unity asset bundle. """ @spec type :: :map def type, do: :map def cast(%Structs.UnityAssetBundle{} = unity_asset_bundle), do: { :ok, unity_asset_bundle } def cast(%{} = map), do: { :ok, from_map map } def cast(nil), do: { :ok, nil } def cast(_), do: :error def load(%{} = map), do: { :ok, from_map map } def dump(%Structs.UnityAssetBundle{} = unity_asset_bundle), do: { :ok, to_map unity_asset_bundle } end