common.ml 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. module D = Decoders_ezjsonm.Decode
  2. let rfc3339 =
  3. let open D in
  4. let* time = string in
  5. match time |> Ptime.of_rfc3339 |> Ptime.rfc3339_error_to_msg with
  6. | Ok (t, _, _) -> succeed t
  7. | Error `Msg err -> fail err
  8. let singleton_or_list dec =
  9. D.(one_of ["singleton", (dec >|= fun v -> [v]);
  10. "list", list dec;
  11. "null", null >|= fun () -> []])
  12. let lossy_list_of dec =
  13. let open D in
  14. list (one_of ["known", (dec >|= fun v -> `Value v)(*; "unknown", value >|= fun v -> `Raw v*)])
  15. let constant ?msg target =
  16. let open D in
  17. let* str = string in
  18. if String.equal str target
  19. then succeed ()
  20. else match msg with
  21. | None -> fail (Printf.sprintf "expected %s received %s" target str)
  22. | Some msg -> fail (Printf.sprintf msg str)
  23. let field_or_default field' decoder default =
  24. let open D in
  25. let+ field = field_opt field' decoder in
  26. Option.value ~default field
  27. let list_ignoring_unknown ty =
  28. let open D in
  29. list (maybe ty) >|= fun v -> List.filter_map Fun.id v
  30. let items obj =
  31. let open D in
  32. one_of [
  33. ("ordered items",
  34. let* items = field "orderedItems" (list obj) in
  35. succeed (true, items));
  36. "items",
  37. let* items = field "items" (list obj) in
  38. succeed (false, items)
  39. ]
  40. let items_opt obj =
  41. let open D in
  42. maybe (items obj)