Auto-indexing service and GraphQL API for AT Protocol Records
quickslice.slices.network/
atproto
gleam
graphql
1/// Cursor encoding/decoding for admin GraphQL connections
2///
3/// Cursors are opaque base64-encoded strings in format "Type:ID"
4/// Example: "Label:42" -> "TGFiZWw6NDI="
5import gleam/bit_array
6import gleam/int
7import gleam/result
8import gleam/string
9
10/// Encode a cursor from prefix and ID
11/// "Label", 42 -> "TGFiZWw6NDI="
12pub fn encode(prefix: String, id: Int) -> String {
13 let raw = prefix <> ":" <> int.to_string(id)
14 bit_array.from_string(raw)
15 |> bit_array.base64_encode(True)
16}
17
18/// Decode a cursor to prefix and ID
19/// "TGFiZWw6NDI=" -> Ok(#("Label", 42))
20pub fn decode(cursor: String) -> Result(#(String, Int), Nil) {
21 use decoded <- result.try(
22 bit_array.base64_decode(cursor)
23 |> result.try(fn(bits) { bit_array.to_string(bits) })
24 |> result.replace_error(Nil),
25 )
26
27 case string.split(decoded, ":") {
28 [prefix, id_str] -> {
29 case int.parse(id_str) {
30 Ok(id) -> Ok(#(prefix, id))
31 Error(_) -> Error(Nil)
32 }
33 }
34 _ -> Error(Nil)
35 }
36}