1 | module main |
2 | |
3 | import vweb |
4 | import time |
5 | import db.sqlite |
6 | |
7 | struct App { |
8 | vweb.Context |
9 | pub mut: |
10 | db sqlite.DB |
11 | user_id string |
12 | } |
13 | |
14 | struct Article { |
15 | id int |
16 | title string |
17 | text string |
18 | } |
19 | |
20 | fn test_a_vweb_application_compiles() { |
21 | spawn fn () { |
22 | time.sleep(2 * time.second) |
23 | exit(0) |
24 | }() |
25 | vweb.run(&App{}, 18081) |
26 | } |
27 | |
28 | pub fn (mut app App) before_request() { |
29 | app.user_id = app.get_cookie('id') or { '0' } |
30 | } |
31 | |
32 | ['/new_article'; post] |
33 | pub fn (mut app App) new_article() vweb.Result { |
34 | title := app.form['title'] |
35 | text := app.form['text'] |
36 | if title == '' || text == '' { |
37 | return app.text('Empty text/title') |
38 | } |
39 | article := Article{ |
40 | title: title |
41 | text: text |
42 | } |
43 | println('posting article') |
44 | println(article) |
45 | sql app.db { |
46 | insert article into Article |
47 | } or {} |
48 | |
49 | return app.redirect('/') |
50 | } |
51 | |
52 | fn (mut app App) time() { |
53 | app.text(time.now().format()) |
54 | } |
55 | |
56 | fn (mut app App) time_json() { |
57 | app.json({ |
58 | 'time': time.now().format() |
59 | }) |
60 | } |
61 | |
62 | fn (mut app App) time_json_pretty() { |
63 | app.json_pretty({ |
64 | 'time': time.now().format() |
65 | }) |
66 | } |
67 | |
68 | struct ApiSuccessResponse[T] { |
69 | success bool |
70 | result T |
71 | } |
72 | |
73 | fn (mut app App) json_success[T](result T) vweb.Result { |
74 | response := ApiSuccessResponse[T]{ |
75 | success: true |
76 | result: result |
77 | } |
78 | |
79 | return app.json(response) |
80 | } |
81 | |
82 | // should compile, this is a helper method, not exposed as a route |
83 | fn (mut app App) some_helper[T](result T) ApiSuccessResponse[T] { |
84 | response := ApiSuccessResponse[T]{ |
85 | success: true |
86 | result: result |
87 | } |
88 | return response |
89 | } |
90 | |
91 | // should compile, the route method itself is not generic |
92 | fn (mut app App) ok() vweb.Result { |
93 | return app.json(app.some_helper(123)) |
94 | } |
95 | |
96 | struct ExampleStruct { |
97 | example int |
98 | } |
99 | |
100 | fn (mut app App) request_raw_2() vweb.Result { |
101 | stuff := []ExampleStruct{} |
102 | return app.request_raw(stuff) |
103 | } |
104 | |
105 | // should compile, this is a helper method, not exposed as a route |
106 | fn (mut app App) request_raw(foo []ExampleStruct) vweb.Result { |
107 | return app.text('Hello world') |
108 | } |