Wednesday, August 12, 2009

Basic Environment Access - Request Helpers

Although we have access to the request object, its current form is not yet as abstracted as what PHP has - let's bring it closer. What we want to do is to write shp scripts like:

`(p ,(url->string ($uri)) ,($query "key"))

The first thing we should do is to create a $request parameter, which we'll fill with

(define $request (make-parameter #f))

The simplest function then is $uri:

(define ($uri)
(request-uri ($request)))

We then add function to handle the key/value pairs of $query, which includes both the url query as well as the post data, and $header for looking up header values.

(define ($header key)
(headers-assq* (string->bytes/utf-8 key) (request-headers/raw ($request))))

(define ($query* key)
(define (helper bindings)
(map (lambda (b)
(if (binding:form? b)
(bytes->string/utf-8 (binding:form-value b))
b))
bindings))
(helper (filter (lambda (binding)
(string-ci=? (bytes->string/utf-8 (binding-id binding))
key))
(request-bindings/raw ($request)))))

(define ($query key)
(let ((vals ($query* key)))
(if (null? vals) #f
(car vals))))

For query - since we can have duplicate values, two forms are provided - $query* to return multiple values, and $query to return singular values (or #f if not found).

To make it all work - we just need to parameterize $request during the calling:

(define (make-shp-handler path
#:default (default "index.shp")
#:not-found (not-found "notfound.shp"))
(lambda (request)
(parameterize (($pathinfo ($pathinfo))
($request request))
(let ((proc (evaluate-terms
(file->values
(url->shp-path (request-uri request) path default not-found)))))
(proc request)))))


There are more accessors to provide, but for now this provide enough $request abstraction.

No comments:

Post a Comment