~pepe/trolley

7ded30571fcac60ac125cf5e32a81c29c5ef226c — Josef Pospíšil 4 years ago 69afbf7
Formatted with spork
1 files changed, 15 insertions(+), 16 deletions(-)

M trolley.janet
M trolley.janet => trolley.janet +15 -16
@@ 1,5 1,5 @@
# @todo: make this dyn
(def chars 
(def chars
  "Characters considered part of the route"
  '(+ :w (set "-_.")))



@@ 12,12 12,12 @@

(def <-: named-capture)

(def grammar 
(def grammar
  "PEG grammar to match routes with"
  (peg/compile
    {:sep sep :pref pref :path ~(some ,chars) 
    {:sep sep :pref pref :path ~(some ,chars)
     :param '(* :pref :path) :capture-path '(<- :path)
     :main ~(some (* :sep 
     :main ~(some (* :sep
                     (+ (if :param ,(<-: :param :pref :capture-path))
                        (if :path ,(<-: :path :capture-path))
                        (if -1 ,(<-: :root '(constant -1))))))}))


@@ 26,11 26,11 @@
  "Compiles custom grammar for one route"
  [route]
  (-> (seq [[pt p] :in (peg/match grammar route)]
           (case pt
             :root (tuple '* sep p)
             :path (tuple '* sep p) 
             :param (tuple '* sep  
                           ~,(<-: p ~(<- (some ,chars))))))
        (case pt
          :root (tuple '* sep p)
          :path (tuple '* sep p)
          :param (tuple '* sep
                        ~,(<-: p ~(<- (some ,chars))))))
      (array/insert 0 '*)
      (array/push -1)
      splice


@@ 47,11 47,11 @@
  "Compiles PEG grammar for all routes"
  [routes]
  (let [res @{}]
    (loop [[route action] :pairs routes] 
        (when (string? route) (put res (compile-route route) action)))
    (loop [[route action] :pairs routes]
      (when (string? route) (put res (compile-route route) action)))
    res))

(defn lookup 
(defn lookup
  "Looks up uri in routes and returns action and params for the matched route"
  [compiled-routes uri]
  (var matched [])


@@ 65,14 65,13 @@
  (def compiled-routes (compile-routes routes))
  (fn [path] (lookup compiled-routes path)))

(defn resolver 
(defn resolver
  "Creates a simple route compiler from routes"
  [routes]
  (def inverted-routes (invert routes))
  (fn [action &opt params] 
  (fn [action &opt params]
    (def template (get inverted-routes action))
    (if params 
    (if params
      (let [params-grammar (seq [[k v] :pairs params] ~(/ (<- (* ":" ,(string k))) ,(string v)))]
        (first (peg/match ~(% (any (+ ,;params-grammar (<- 1)))) template)))
      template)))