require "./handler" module Guff record APIContext, context : HTTP::Server::Context, model : Model API = { "posts": { "get_posts": { text: "Get posts matching query.", args: { "q": { text: "Search string.", type: :text, required: false, default: "", }, "page": { text: "Page number", type: :int, required: false, default: "1", }, "tags": { text: "Comma-separated list of tags (union)", type: :tags, required: false, default: "1", }, "sort": { text: "Sort order of results", type: :sort, required: false, default: "date,desc", }, }, method: ->(c : APIContext) { "get_posts" } }, }, } API_PATH_RE = %r{ ^/api (?: # method call (?: / (?[a-z0-9_-]+) / (?[a-z0-9]+) ) | # index.html /(?:index(?:\.html|)|) | # implicit index (no trailing slash) ) $ }mx class APIHandler < Handler def call(context : HTTP::Server::Context) if md = (context.request.path || "").match(API_PATH_RE) if md["namespace"]? # method call do_call(context, md["namespace"], md["method"]) else # api index do_docs(context) end else call_next(context) end end private def do_call( context : HTTP::Server::Context, namespace : String, method : String ) # method call # # fn = API[namespace][method][:method] as Proc(APIContext, String) # context.response.puts fn.call(APIContext.new(context, @model)) # page = HTMLPageView.new( "TODO: API Call", "

API Call: namespace = %s, call = %s

" % [ namespace, method ] ) context.response.content_type = page.content_type context.response.puts page end private def do_docs(context : HTTP::Server::Context) page = HTMLPageView.new( "API Documentation", "

API Documentation

" ) context.response.content_type = page.content_type context.response.puts page end end end