-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrequest.gleam
More file actions
79 lines (73 loc) · 2.14 KB
/
request.gleam
File metadata and controls
79 lines (73 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import database
import gleam/int
import gleam/json
import gleam/list
import gleam/string_builder
import svg
import wisp
fn middleware(request, handle) {
let request = wisp.method_override(request)
use <- wisp.log_request(request)
use <- wisp.rescue_crashes
use request <- wisp.handle_head(request)
handle(request)
}
pub fn handle(request, connection, image_cache, index_html) {
use _ <- middleware(request)
case wisp.path_segments(request) {
[] ->
case index_html {
"" -> wisp.not_found()
content -> wisp.html_response(string_builder.from_string(content), 200)
}
["heart-beat"] ->
wisp.html_response(string_builder.from_string("alive"), 200)
["get", "@" <> name] -> {
case database.get_counter(connection, name) {
Ok(counter) -> {
let query = wisp.get_query(request)
wisp.ok()
|> wisp.set_header("Content-Type", "image/svg+xml")
|> wisp.string_body(
svg.xml(
image_cache,
case list.key_find(query, "theme") {
Ok(theme) -> theme
_ -> "asoul"
},
counter.num,
case list.key_find(query, "padding") {
Ok(padding) ->
case int.parse(padding) {
Ok(n) -> int.clamp(n, min: 0, max: 32)
Error(_) -> 6
}
_ -> 6
},
),
)
}
Error(_) -> wisp.unprocessable_entity()
}
}
["record", "@" <> name] -> {
case database.get_counter(connection, name) {
Ok(counter) -> {
wisp.json_response(
json.to_string_builder(
json.object([
#("name", json.string(counter.name)),
#("num", json.int(counter.num)),
#("updated_at", json.string(counter.updated_at)),
#("created_at", json.string(counter.created_at)),
]),
),
200,
)
}
Error(_) -> wisp.unprocessable_entity()
}
}
_ -> wisp.redirect("https://github.com/Fuwn/mayu")
}
}