v / vlib / vweb
Raw file | 108 loc (90 sloc) | 1.86 KB | Latest commit hash 64558df76
1module main
2
3import vweb
4import time
5import db.sqlite
6
7struct App {
8 vweb.Context
9pub mut:
10 db sqlite.DB
11 user_id string
12}
13
14struct Article {
15 id int
16 title string
17 text string
18}
19
20fn 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
28pub fn (mut app App) before_request() {
29 app.user_id = app.get_cookie('id') or { '0' }
30}
31
32['/new_article'; post]
33pub 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
52fn (mut app App) time() {
53 app.text(time.now().format())
54}
55
56fn (mut app App) time_json() {
57 app.json({
58 'time': time.now().format()
59 })
60}
61
62fn (mut app App) time_json_pretty() {
63 app.json_pretty({
64 'time': time.now().format()
65 })
66}
67
68struct ApiSuccessResponse[T] {
69 success bool
70 result T
71}
72
73fn (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
83fn (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
92fn (mut app App) ok() vweb.Result {
93 return app.json(app.some_helper(123))
94}
95
96struct ExampleStruct {
97 example int
98}
99
100fn (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
106fn (mut app App) request_raw(foo []ExampleStruct) vweb.Result {
107 return app.text('Hello world')
108}