memEx/lib/memex/pipelines/pipeline.ex

71 lines
2.1 KiB
Elixir
Raw Normal View History

2022-07-25 20:12:11 -04:00
defmodule Memex.Pipelines.Pipeline do
2022-11-24 14:31:16 -05:00
@moduledoc """
Represents a chain of considerations to take to accomplish a task
"""
2022-07-25 20:12:11 -04:00
use Ecto.Schema
import Ecto.Changeset
2022-11-24 14:31:16 -05:00
alias Ecto.{Changeset, UUID}
2022-11-24 15:35:29 -05:00
alias Memex.{Accounts.User, Pipelines.Step}
2022-07-25 20:12:11 -04:00
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "pipelines" do
field :title, :string
2022-11-24 14:31:16 -05:00
field :description, :string
field :tags, {:array, :string}
field :tags_string, :string, virtual: true
2022-07-25 20:12:11 -04:00
field :visibility, Ecto.Enum, values: [:public, :private, :unlisted]
2022-11-24 14:31:16 -05:00
belongs_to :user, User
2022-11-24 15:35:29 -05:00
has_many :steps, Step, preload_order: [asc: :position]
2022-07-25 20:12:11 -04:00
timestamps()
end
2022-11-24 14:31:16 -05:00
@type t :: %__MODULE__{
title: String.t(),
description: String.t(),
tags: [String.t()] | nil,
tags_string: String.t(),
visibility: :public | :private | :unlisted,
user: User.t() | Ecto.Association.NotLoaded.t(),
user_id: User.id(),
inserted_at: NaiveDateTime.t(),
updated_at: NaiveDateTime.t()
}
@type id :: UUID.t()
@type changeset :: Changeset.t(t())
2022-07-25 20:12:11 -04:00
@doc false
2022-11-24 14:31:16 -05:00
@spec create_changeset(attrs :: map(), User.t()) :: changeset()
def create_changeset(attrs, %User{id: user_id}) do
%__MODULE__{}
|> cast(attrs, [:title, :description, :tags, :visibility])
|> change(user_id: user_id)
|> cast_tags_string(attrs)
|> validate_required([:title, :user_id, :visibility])
end
@spec update_changeset(t(), attrs :: map(), User.t()) :: changeset()
def update_changeset(%{user_id: user_id} = pipeline, attrs, %User{id: user_id}) do
2022-07-25 20:12:11 -04:00
pipeline
2022-11-24 14:31:16 -05:00
|> cast(attrs, [:title, :description, :tags, :visibility])
|> cast_tags_string(attrs)
|> validate_required([:title, :visibility])
2022-07-25 20:12:11 -04:00
end
2022-11-24 14:31:16 -05:00
defp cast_tags_string(changeset, %{"tags_string" => tags_string})
when tags_string |> is_binary() do
tags =
tags_string
|> String.split(",", trim: true)
|> Enum.map(fn str -> str |> String.trim() end)
|> Enum.sort()
changeset |> change(tags: tags)
end
defp cast_tags_string(changeset, _attrs), do: changeset
2022-07-25 20:12:11 -04:00
end