Skip to content

Instantly share code, notes, and snippets.

@minikomi
Created March 31, 2014 10:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minikomi/9889335 to your computer and use it in GitHub Desktop.
Save minikomi/9889335 to your computer and use it in GitHub Desktop.
clojure sprunge-like for GAE
(ns sprulj.core
(:use compojure.core
[appengine-magic.multipart-params :only [wrap-multipart-params]])
(:require [appengine-magic.core :as ae]
[appengine-magic.services.datastore :as ds]
))
(def VALID-CHARS
(->>
(concat (range 48 58)
(range 65 91)
(range 97 123))
(map char)))
(def URL "http://localhost:8080")
(defn- new-id []
(->>
(repeatedly #(rand-nth VALID-CHARS))
(take 4)
(apply str)))
(ds/defentity Entry [^{:tag :key} name, data, date])
(defroutes sprulj-app-handler
(GET "/" req
{:status 200
:headers {"Content-Type" "text/plain"}
:body "hi"})
(GET "/:id" [id]
{:status 200
:headers {"Content-Type" "text/plain"}
:body
(if-let [entry (ds/query :kind Entry :filter (= :name id))]
(:data (first entry))
"Not found.")})
(POST "/" _
(wrap-multipart-params
(fn [req]
(if-let [data ((req :params ) "data")]
; data ok ------------------------------------------------------
(let [id (first
(filter
#(not (ds/exists? Entry %))
(repeatedly new-id)))
new-entry (Entry. id data (new java.util.Date))
current-count (ds/query :kind Entry :count-only? true)]
(when (> current-count 199)
(ds/delete!
(ds/query :kind Entry
:sort :date
:limit (- current-count 199))))
(ds/save! new-entry)
{:status 200
:headers {"Content-Type" "text/plain"}
:body (format "%s.%s/%s\n"
(ae/appengine-app-id)
(ae/appengine-base-url)
id)})
; bad request ---------------------------------------------------
{:status 400})))))
(ae/def-appengine-app sprulj-app #'sprulj-app-handler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment