nit: Added link to `CONTRIBUTING.md` from the README
[nit.git] / src / web / web_base.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Base classes used by `nitweb`.
16 module web_base
17
18 import model::model_views
19 import model::model_json
20 import popcorn
21
22 # Specific nitcorn Action that uses a Model
23 class ModelAction
24 super Handler
25
26 # Model to use.
27 var model: Model
28
29 # Find the MEntity ` with `full_name`.
30 fun find_mentity(model: ModelView, full_name: nullable String): nullable MEntity do
31 if full_name == null then return null
32 return model.mentity_by_full_name(full_name.from_percent_encoding)
33 end
34
35 # Init the model view from the `req` uri parameters.
36 fun init_model_view(req: HttpRequest): ModelView do
37 var view = new ModelView(model)
38 var show_private = req.bool_arg("private") or else false
39 if not show_private then view.min_visibility = protected_visibility
40
41 view.include_fictive = req.bool_arg("fictive") or else false
42 view.include_empty_doc = req.bool_arg("empty-doc") or else true
43 view.include_test_suite = req.bool_arg("test-suite") or else false
44 view.include_attribute = req.bool_arg("attributes") or else true
45
46 return view
47 end
48 end
49
50 # A NitView is rendered by an action.
51 interface NitView
52 # Renders this view and returns something that can be written to a HTTP response.
53 fun render: Writable is abstract
54 end
55
56 redef class HttpResponse
57 # Render a NitView as response.
58 fun send_view(view: NitView, status: nullable Int) do send(view.render, status)
59 end
60
61 redef class HttpRequest
62 # Does the client asked for a json formatted response?
63 #
64 # Checks the URL get parameter `?json=true`.
65 fun is_json_asked: Bool do return bool_arg("json") or else false
66 end