diff --git a/app/controllers/link.cr b/app/controllers/link.cr index b6dcdbf..50c2b9e 100644 --- a/app/controllers/link.cr +++ b/app/controllers/link.cr @@ -97,10 +97,30 @@ module App::Controllers::Link def call(env) user = env.get("user").as(User) - query = Database::Query.where(user_id: user.id.as(String)) - links = Database.all(Link, query, preload: [:clicks]) + limit = (env.params.query["limit"]? || "100").to_i + cursor = env.params.query["cursor"]? + + query = Database::Query.where(user_id: user.id.as(String)) + if cursor + query = query.where("id < ?", cursor) + end + + query = query.order_by("id DESC").limit(limit + 1) + links = Database.all(Link, query) + + has_more = links.size > limit + links = links[0...limit] if has_more + + next_cursor = has_more ? links.last.id : nil + + response = { + "data" => links.map { |link| App::Serializers::Link.new(link) }, + "pagination" => { + "has_more" => has_more, + "next" => next_cursor + } + } - response = {"data" => links.map { |link| App::Serializers::Link.new(link) }} response.to_json end end diff --git a/app/serializers/link.cr b/app/serializers/link.cr index 60ec040..f77410b 100644 --- a/app/serializers/link.cr +++ b/app/serializers/link.cr @@ -16,7 +16,10 @@ module App::Serializers builder.field("id", @link.id) builder.field("refer", @refer) builder.field("origin", @link.url) - builder.field("clicks", @link.clicks.map { |click| App::Serializers::Click.new(click) }) + + unless @link.clicks.empty? + builder.field("clicks", @link.clicks.map { |click| App::Serializers::Click.new(click) }) + end end end end