diff --git a/src/library/title.cr b/src/library/title.cr index 2d4e347..0b91603 100644 --- a/src/library/title.cr +++ b/src/library/title.cr @@ -63,7 +63,10 @@ class Title end end - def build_json(json : JSON::Builder, *, slim = false, shallow = false) + alias SortContext = NamedTuple(username: String, opt: SortOptions) + + def build_json(json : JSON::Builder, *, slim = false, shallow = false, + sort_context : SortContext? = nil) json.object do {% for str in ["dir", "title", "id"] %} json.field {{str}}, @{{str.id}} @@ -87,7 +90,13 @@ class Title end json.field "entries" do json.array do - @entries.each do |entry| + _entries = if sort_context + sorted_entries sort_context[:username], + sort_context[:opt] + else + @entries + end + _entries.each do |entry| raw = JSON.build do |j| entry.build_json j, slim: slim end diff --git a/src/routes/api.cr b/src/routes/api.cr index 924085b..3dc878e 100644 --- a/src/routes/api.cr +++ b/src/routes/api.cr @@ -139,11 +139,18 @@ struct APIRouter Koa.path "tid", desc: "Title ID" Koa.query "slim" Koa.query "shallow" + Koa.query "sort", desc: "Sorting option for entries. Can be one of 'auto', 'title', 'progress', 'time_added' and 'time_modified'" + Koa.query "ascend", desc: "Sorting direction for entries. Set to 0 for the descending order. Doesn't work without specifying 'sort'" Koa.response 200, schema: "title" Koa.response 404, "Title not found" Koa.tag "library" get "/api/book/:tid" do |env| begin + username = get_username env + + sort_opt = SortOptions.new + get_sort_opt + tid = env.params.url["tid"] title = Library.default.get_title tid raise "Title ID `#{tid}` not found" if title.nil? @@ -152,7 +159,8 @@ struct APIRouter shallow = !env.params.query["shallow"]?.nil? json = JSON.build do |j| - title.build_json j, slim: slim, shallow: shallow + title.build_json j, slim: slim, shallow: shallow, + sort_context: {username: username, opt: sort_opt} end rescue e Logger.error e