Simplify #json_build

This commit is contained in:
Alex Ling 2021-09-14 02:30:57 +00:00
parent 4b464ed361
commit 4eaf271fa4
4 changed files with 55 additions and 62 deletions

View File

@ -46,7 +46,8 @@ class Entry
file.close
end
def build_json(json : JSON::Builder, *, slim = false)
def build_json(*, slim = false)
JSON.build do |json|
json.object do
{% for str in ["zip_path", "title", "size", "id"] %}
json.field {{str}}, @{{str.id}}
@ -60,6 +61,7 @@ class Entry
end
end
end
end
def display_name
@book.display_name @title

View File

@ -65,16 +65,15 @@ class Library
titles.flat_map &.deep_entries
end
def build_json(json : JSON::Builder, *, slim = false, shallow = false)
def build_json(*, slim = false, shallow = false)
JSON.build do |json|
json.object do
json.field "dir", @dir
json.field "titles" do
json.array do
self.titles.each do |title|
raw = JSON.build do |j|
title.build_json j, slim: slim, shallow: shallow
json.raw title.build_json(slim: slim, shallow: shallow)
end
json.raw raw
end
end
end

View File

@ -65,8 +65,9 @@ class Title
alias SortContext = NamedTuple(username: String, opt: SortOptions)
def build_json(json : JSON::Builder, *, slim = false, shallow = false,
def build_json(*, slim = false, shallow = false,
sort_context : SortContext? = nil)
JSON.build do |json|
json.object do
{% for str in ["dir", "title", "id"] %}
json.field {{str}}, @{{str.id}}
@ -81,10 +82,7 @@ class Title
json.field "titles" do
json.array do
self.titles.each do |title|
raw = JSON.build do |j|
title.build_json j, slim: slim, shallow: shallow
end
json.raw raw
json.raw title.build_json(slim: slim, shallow: shallow)
end
end
end
@ -97,10 +95,7 @@ class Title
@entries
end
_entries.each do |entry|
raw = JSON.build do |j|
entry.build_json j, slim: slim
end
json.raw raw
json.raw entry.build_json(slim: slim)
end
end
end
@ -117,6 +112,7 @@ class Title
end
end
end
end
def titles
@title_ids.map { |tid| Library.default.get_title! tid }

View File

@ -158,10 +158,9 @@ struct APIRouter
slim = !env.params.query["slim"]?.nil?
shallow = !env.params.query["shallow"]?.nil?
json = JSON.build do |j|
title.build_json j, slim: slim, shallow: shallow,
sort_context: {username: username, opt: sort_opt}
end
send_json env, title.build_json(slim: slim, shallow: shallow,
sort_context: {username: username,
opt: sort_opt})
rescue e
Logger.error e
env.response.status_code = 404
@ -184,10 +183,7 @@ struct APIRouter
slim = !env.params.query["slim"]?.nil?
shallow = !env.params.query["shallow"]?.nil?
json = JSON.build do |j|
Library.default.build_json j, slim: slim, shallow: shallow
end
send_json env, json
send_json env, Library.default.build_json(slim: slim, shallow: shallow)
end
Koa.describe "Triggers a library scan"