From 51c67b3da6a832396372beae64751dca1d93b8a0 Mon Sep 17 00:00:00 2001 From: Omar Roth Date: Wed, 18 Sep 2019 14:19:53 -0400 Subject: [PATCH] Support 'sort_by' in JSON response --- src/instances.cr | 52 +++++++++++++++++++++-------------- src/instances/views/index.ecr | 2 +- 2 files changed, 32 insertions(+), 22 deletions(-) diff --git a/src/instances.cr b/src/instances.cr index 21685dc..52bd6b8 100644 --- a/src/instances.cr +++ b/src/instances.cr @@ -95,8 +95,37 @@ get "/" do |env| sort_by = env.params.query["sort_by"]? sort_by ||= "users" + instances = sort_instances(INSTANCES, sort_by) + + rendered "index" +end + +get "/instances.json" do |env| + env.response.content_type = "application/json; charset=utf-8" + sort_by = env.params.query["sort_by"]? + sort_by ||= "users" + + instances = sort_instances(INSTANCES, sort_by) + + if env.params.query["pretty"]?.try &.== "1" + instances.to_pretty_json + else + instances.to_json + end +end + +error 404 do |env| + env.redirect "/" + halt env, status_code: 302, response: "" +end + +static_headers do |response, filepath, filestat| + response.headers.add("Cache-Control", "max-age=86400") +end + +def sort_instances(instances, sort_by) sort_proc = ->(instance : Tuple(String, Instance)) { instance[0] } - instances = INSTANCES.dup.to_a + instances = instances.to_a case sort_by when .starts_with? "name" @@ -116,26 +145,7 @@ get "/" do |env| end instances.reverse! if sort_by.ends_with?("-reverse") - rendered "index" -end - -get "/instances.json" do |env| - env.response.content_type = "application/json; charset=utf-8" - - if env.params.query["pretty"]?.try &.== "1" - INSTANCES.to_pretty_json - else - INSTANCES.to_json - end -end - -error 404 do |env| - env.redirect "/" - halt env, status_code: 302, response: "" -end - -static_headers do |response, filepath, filestat| - response.headers.add("Cache-Control", "max-age=86400") + instances end gzip true diff --git a/src/instances/views/index.ecr b/src/instances/views/index.ecr index 24bcf27..1dc6330 100644 --- a/src/instances/views/index.ecr +++ b/src/instances/views/index.ecr @@ -52,7 +52,7 @@

Add your instance here. - JSON + &sort_by=<%= sort_by %><% end %>">JSON