JOL/priv/migrate_posts.exs

27 lines
752 B
Elixir

alias JOL.Blog.{Parser,Post,Tag}
alias JOL.Repo
import Ecto.Query
post_dir = Application.app_dir(:jol, "priv/posts/blog/")
Path.wildcard("#{post_dir}/**/*.md")
|> Enum.each(fn path ->
{attrs, body} = Parser.parse(path, File.read!(path))
for tag <- attrs.tags do
Repo.insert!(%Tag{name: tag}, on_conflict: :nothing, conflict_target: [:name])
end
post_attrs = %{title: attrs.title,
published_at: attrs.date,
slug: attrs.slug,
body: body,
tags: Repo.all(from t in Tag, where: t.name in ^attrs.tags)
}
%Post{}
|> Repo.preload(:tags)
|> Ecto.Changeset.cast(post_attrs, [:published_at, :slug, :body, :title])
|> Ecto.Changeset.put_assoc(:tags, post_attrs.tags)
|> Repo.insert!()
end)