Initdata.res

 1// compact: mirrors types set in server/user/user.go (User type)
 2// and returned from server/pages/edit.go (InitData type)
 3// and State.user + State.readonly
 4type t = {
 5  id: string,
 6  email: string,
 7  handle: string,
 8  registered: bool,
 9  readonly: bool,
10}
11
12@get external textContent: Dom.element => string = "textContent"
13
14let decodeInitdata = (json: JSON.t): option<t> => {
15  switch json->JSON.Decode.object {
16  | Some(dict) => {
17      let id = dict->Dict.get("id")->Option.flatMap(JSON.Decode.string)
18      let handle = dict->Dict.get("handle")->Option.flatMap(JSON.Decode.string)
19      let registered = dict->Dict.get("registered")->Option.flatMap(JSON.Decode.bool)
20      let readonly = dict->Dict.get("readonly")->Option.flatMap(JSON.Decode.bool)
21      let email = dict->Dict.get("email")->Option.flatMap(JSON.Decode.string)
22      switch (id, email, handle, registered, readonly) {
23      | (Some(id), Some(email), Some(handle), Some(registered), Some(readonly)) =>
24        Some({id, email, handle, registered, readonly})
25      | _ => None
26      }
27    }
28  | None => None
29  }
30}
31
32let getInitdata: unit => option<t> = () => {
33  switch Doc.querySelector("#initdata")->Nullable.toOption {
34  | Some(elem) => {
35      Console.log2("got initdata elem", elem)
36      let text = elem->textContent->String.trim
37      if text == "" {
38        None
39      } else {
40        try {
41          JSON.parseExn(text)->decodeInitdata
42        } catch {
43        | _ => None
44        }
45      }
46    }
47  | None => None
48  }
49}