2024-05-21 16:52:37 +00:00
|
|
|
defmodule JOL.Blog do
|
|
|
|
alias JOL.Blog.Post
|
2024-07-30 15:46:47 +00:00
|
|
|
alias JOL.Blog.Parser
|
2024-07-30 15:51:18 +00:00
|
|
|
|
2024-06-04 18:09:14 +00:00
|
|
|
defmodule NotFoundError do
|
|
|
|
defexception [:message, plug_status: 404]
|
|
|
|
end
|
2024-05-21 16:43:36 +00:00
|
|
|
|
|
|
|
use NimblePublisher,
|
2024-08-17 13:19:42 +00:00
|
|
|
build: Post,
|
2024-05-27 17:18:57 +00:00
|
|
|
from: Application.app_dir(:jol, "priv/posts/**/*.md"),
|
2024-07-30 15:46:47 +00:00
|
|
|
parser: Parser,
|
2024-07-30 15:51:18 +00:00
|
|
|
as: :posts
|
2024-05-21 16:43:36 +00:00
|
|
|
|
|
|
|
@posts Enum.sort_by(@posts, & &1.date, {:desc, Date})
|
|
|
|
@tags @posts |> Enum.flat_map(& &1.tags) |> Enum.uniq() |> Enum.sort()
|
|
|
|
|
2024-08-17 13:19:42 +00:00
|
|
|
@spec all_posts() :: [
|
|
|
|
%Post{
|
|
|
|
author: String.t(),
|
|
|
|
body: String.t(),
|
|
|
|
date: DateTime.t(),
|
|
|
|
draft: false | nil,
|
|
|
|
slug: String.t(),
|
|
|
|
tags: [String.t()],
|
|
|
|
title: String.t()
|
|
|
|
}
|
|
|
|
]
|
2024-06-04 18:09:14 +00:00
|
|
|
def all_posts, do: @posts
|
2024-05-21 16:43:36 +00:00
|
|
|
def unique_tag_list, do: @tags
|
2024-06-04 18:09:14 +00:00
|
|
|
|
|
|
|
def recent_posts(num \\ 10) do
|
|
|
|
Enum.take(all_posts(), num)
|
|
|
|
end
|
|
|
|
|
|
|
|
def get_post_by_slug!(slug) do
|
|
|
|
Enum.find(all_posts(), &(&1.slug == slug)) ||
|
|
|
|
raise NotFoundError, "post ``slug=#{slug}` not found"
|
|
|
|
end
|
|
|
|
|
|
|
|
def get_posts_by_tag!(tag) do
|
|
|
|
case Enum.filter(all_posts(), &(tag in &1.tags)) do
|
|
|
|
[] -> raise NotFoundError, "posts tagged `#{tag}` not found"
|
|
|
|
posts -> posts
|
|
|
|
end
|
|
|
|
end
|
2024-08-25 16:56:26 +00:00
|
|
|
|
|
|
|
def format_date(date) do
|
|
|
|
Calendar.strftime(date, "%Y-%m-%d")
|
|
|
|
end
|
2024-05-21 16:43:36 +00:00
|
|
|
end
|