aboutsummaryrefslogtreecommitdiff
path: root/src/guff/api-handler.cr
diff options
context:
space:
mode:
authorPaul Duncan <pabs@pablotron.org>2016-03-05 23:08:26 -0500
committerPaul Duncan <pabs@pablotron.org>2016-03-05 23:08:26 -0500
commit1e7f2784a13492da87c8351171e7355dd068bd79 (patch)
treefdd6b3e2f7c3b08ed6e971b7f00128c06eb29025 /src/guff/api-handler.cr
parent0c003fc2985c5ce0a2d04026d63ab7265ce9af94 (diff)
downloadold-guff-1e7f2784a13492da87c8351171e7355dd068bd79.tar.bz2
old-guff-1e7f2784a13492da87c8351171e7355dd068bd79.zip
add api and test handlers, refactor config
Diffstat (limited to 'src/guff/api-handler.cr')
-rw-r--r--src/guff/api-handler.cr122
1 files changed, 122 insertions, 0 deletions
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
+ (?:
+ /
+ (?<namespace>[a-z0-9_-]+)
+ /
+ (?<method>[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",
+ "<p>API Call: namespace = %s, call = %s</p>" % [
+ 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",
+ "<p>API Documentation</p>"
+ )
+
+ context.response.content_type = page.content_type
+ context.response.puts page
+ end
+ end
+end