aboutsummaryrefslogtreecommitdiff
path: root/src/guff/api-handler.cr
diff options
context:
space:
mode:
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