1 ! Copyright (C) 2008, 2009 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors assocs combinators fry furnace.conversations
4 furnace.utilities html.forms http http.server
5 http.server.responses kernel namespaces sequences splitting urls
7 FROM: html.templates.chloe => <chloe> ;
12 TUPLE: action rest init authorize display validate submit update replace ;
14 : new-action ( class -- action )
15 new [ ] >>init [ ] >>validate [ ] >>authorize ; inline
17 : <action> ( -- action )
20 : merge-forms ( form -- )
22 [ [ errors>> ] bi@ append! drop ]
23 [ [ values>> ] bi@ assoc-union! drop ]
24 [ validation-failed>> >>validation-failed drop ]
27 : set-nested-form ( form name -- )
31 unclip [ set-nested-form ] nest-form
34 : restore-validation-errors ( -- )
36 nested-forms cget set-nested-form
39 : handle-get ( action -- response )
44 [ authorize>> call( -- ) ]
45 [ drop restore-validation-errors ]
46 [ display>> call( -- response ) ]
49 ] with-exit-continuation ;
51 CONSTANT: revalidate-url-key "__u"
53 : revalidate-url ( -- url/f )
54 revalidate-url-key param
55 dup [ >url ensure-port [ same-host? ] keep and ] when ;
57 : validation-failed ( -- * )
58 post-request? revalidate-url and [
60 nested-forms-key param " " split harvest nested-forms cset
62 <continue-conversation>
66 : handle-post ( action -- response )
69 [ validate>> call( -- ) ]
70 [ authorize>> call( -- ) ]
71 [ submit>> call( -- response ) ]
74 ] with-exit-continuation ;
76 : handle-put ( action -- response )
79 [ validate>> call( -- ) ]
80 [ authorize>> call( -- ) ]
81 [ replace>> call( -- response ) ]
84 ] with-exit-continuation ;
86 : handle-patch ( action -- response )
89 [ validate>> call( -- ) ]
90 [ authorize>> call( -- ) ]
91 [ update>> call( -- response ) ]
94 ] with-exit-continuation ;
96 : handle-rest ( path action -- )
97 rest>> [ [ "/" join ] dip set-param ] [ drop ] if* ;
99 : init-action ( path action -- )
103 M: action call-responder*
105 request get method>> {
106 { "GET" [ handle-get ] }
107 { "HEAD" [ handle-get ] }
108 { "POST" [ handle-post ] }
109 { "PUT" [ handle-put ] }
110 { "PATCH" [ handle-patch ] }
114 M: action modify-form
115 drop url get revalidate-url-key hidden-form-field ;
117 : check-validation ( -- )
118 validation-failed? [ validation-failed ] when ;
120 : validate-params ( validators -- )
121 params get swap validate-values check-validation ;
123 : validate-integer-id ( -- )
124 { { "id" [ v-number ] } } validate-params ;
126 TUPLE: page-action < action template ;
128 : <chloe-content> ( path -- response )
129 resolve-template-path <chloe> <html-content> ;
131 : <page-action> ( -- page )
132 page-action new-action
133 dup '[ _ template>> <chloe-content> ] >>display ;