JOL/lib/jol/blog.ex

48 lines
1.1 KiB
Elixir

defmodule JOL.Blog do
alias JOL.Blog.Post
alias JOL.Blog.Parser
defmodule NotFoundError do
defexception [:message, plug_status: 404]
end
use NimblePublisher,
build: Post,
from: Application.app_dir(:jol, "priv/posts/**/*.md"),
parser: Parser,
as: :posts
@posts Enum.sort_by(@posts, & &1.date, {:desc, Date})
@tags @posts |> Enum.flat_map(& &1.tags) |> Enum.uniq() |> Enum.sort()
@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()
}
]
def all_posts, do: @posts
def unique_tag_list, do: @tags
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
end