diff --git a/lib/pescarte/blog/entity/tag.ex b/lib/pescarte/blog/entity/tag.ex index 71cb09e3..07c0a5e9 100644 --- a/lib/pescarte/blog/entity/tag.ex +++ b/lib/pescarte/blog/entity/tag.ex @@ -43,6 +43,17 @@ defmodule Pescarte.Blog.Entity.Tag do Pescarte.Database.fetch_by(Tag, nome: nome) end + @spec upsert_tag(list(Tag.t())) :: {:ok, Tag.t()} + def upsert_tag(tags) do + for t <- tags do + Repo.insert!( + %Tag{nome: t}, + on_conflict: [set: [nome: t]], + conflict_target: :nome + ) + end + end + @spec create_tag(map()) :: {:ok, Tag.t()} | {:error, changeset} def create_tag(attrs) do %Tag{} diff --git a/lib/pescarte/blog/post.ex b/lib/pescarte/blog/post.ex index d6c49a47..b4b4f97a 100644 --- a/lib/pescarte/blog/post.ex +++ b/lib/pescarte/blog/post.ex @@ -2,6 +2,7 @@ defmodule Pescarte.Blog.Post do @moduledoc """ Módulo que define o schema e o changeset para os posts. """ + alias Ecto.Multi alias Pescarte.Blog.Entity.Tag alias Pescarte.Database alias Pescarte.Database.Repo @@ -54,11 +55,19 @@ defmodule Pescarte.Blog.Post do Database.fetch(Post, id) end + # @spec create_post(Post.t()) :: {:ok, Post.t()} | {:error, Ecto.Changeset.t()} + # def create_post(params) do + # %Post{} + # |> Post.changeset(params) + # |> Repo.insert() + # end + @spec create_post(Post.t()) :: {:ok, Post.t()} | {:error, Ecto.Changeset.t()} - def create_post(params) do - %Post{} - |> Post.changeset(params) - |> Repo.insert() + def create_post(%Post{blog_tags: tags} = params) do + Multi.new() + |> Multi.update(:blog_tag, Tag.upsert_tag(tags)) + # fazer upload da capa da imagem via o Client da Supabase Storage a ser criado + |> Multi.insert(:blog_post, Post.changeset(%Post{}, params)) end @spec delete_post(String.t()) :: {:ok, Post.t()} | {:error, :not_found}