馃 A practical web framework for Gleam
1import gleam/dict.{type Dict}
2import gleam/dynamic
3import gleam/json
4import gleam/list
5import gleam/result
6import simplifile
7import youid/uuid
8
9pub opaque type Connection {
10 Connection(root: String)
11}
12
13pub fn connect(root: String) -> Connection {
14 let assert Ok(_) = simplifile.create_directory_all(root)
15 Connection(root)
16}
17
18pub fn disconnect(_connection: Connection) -> Nil {
19 // Here we do nothing, but a real database would close the connection or do
20 // some other teardown.
21 Nil
22}
23
24pub fn with_connection(root: String, f: fn(Connection) -> t) -> t {
25 let connection = connect(root)
26 let result = f(connection)
27 disconnect(connection)
28 result
29}
30
31pub fn truncate(connection: Connection) -> Result(Nil, Nil) {
32 let assert Ok(_) = simplifile.delete(connection.root)
33 Ok(Nil)
34}
35
36pub fn list(connection: Connection) -> Result(List(String), Nil) {
37 let assert Ok(_) = simplifile.create_directory_all(connection.root)
38 simplifile.read_directory(connection.root)
39 |> result.nil_error
40}
41
42pub fn insert(
43 connection: Connection,
44 values: Dict(String, String),
45) -> Result(String, Nil) {
46 let assert Ok(_) = simplifile.create_directory_all(connection.root)
47 let id = uuid.v4_string()
48 let values =
49 values
50 |> dict.to_list
51 |> list.map(fn(pair) { #(pair.0, json.string(pair.1)) })
52 let json = json.to_string(json.object(values))
53 use _ <- result.try(
54 simplifile.write(file_path(connection, id), json)
55 |> result.nil_error,
56 )
57 Ok(id)
58}
59
60pub fn read(
61 connection: Connection,
62 id: String,
63) -> Result(Dict(String, String), Nil) {
64 use data <- result.try(
65 simplifile.read(file_path(connection, id))
66 |> result.nil_error,
67 )
68
69 let decoder = dynamic.dict(dynamic.string, dynamic.string)
70
71 use data <- result.try(
72 json.decode(data, decoder)
73 |> result.nil_error,
74 )
75
76 Ok(data)
77}
78
79fn file_path(connection: Connection, id: String) -> String {
80 connection.root <> "/" <> id
81}