From 1e7f2784a13492da87c8351171e7355dd068bd79 Mon Sep 17 00:00:00 2001 From: Paul Duncan Date: Sat, 5 Mar 2016 23:08:26 -0500 Subject: add api and test handlers, refactor config --- src/guff/api-handler.cr | 122 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 src/guff/api-handler.cr (limited to 'src/guff/api-handler.cr') diff --git a/src/guff/api-handler.cr b/src/guff/api-handler.cr new file mode 100644 index 0000000..7928d3c --- /dev/null +++ b/src/guff/api-handler.cr @@ -0,0 +1,122 @@ +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 -- cgit v1.2.3