Source file param.ml

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
80
81
82
83
84
85
86
open Printf
open Util

type t = Swagger_j.parameter

let rec item_kind_to_string (items : Swagger_j.items option) = function
  | `String  -> "string"
  | `Number  -> "float"
  | `Integer -> "int"
  | `Boolean -> "bool"
  | `Array   ->
      let open Swagger_j in
      match items with
      | Some is -> item_kind_to_string is.items is.kind ^ " list"
      | None -> failwith ("item_kind_to_string: array type must have an "
                          ^ "'items' field")

let kind_to_string (p : t) =
  match some p.kind with
  | `String  -> "string"
  | `Number  -> "float"
  | `Integer -> "int"
  | `Boolean -> "bool"
  | `File -> "file"
  | `Array   ->
      let open Swagger_j in
      match p.items with
      | Some items -> item_kind_to_string items.items items.kind ^ " array"
      | None -> failwith ("Param.kind_to_string: array type must have an "
                          ^ "'items' field")

let is_keyword = function
  | "external"
  | "object"
  | "to"
  | "type" -> true
  | _ -> false

let name n =
  let n =
    if n.[0] = '$' then String.sub n 1 (String.length n - 1)
    else n in
  let n = snake_case n |> String.lowercase_ascii in
  if is_keyword n then n ^ "_"
  else n

(* Unused values. *)
[@@@ocaml.warning "-32"]

let prefix_strings required =
  if required
  then ("", "~")
  else ("?", "?")

let kind = function
  | true -> `Named
  | false -> `Optional

[@@@end]

let string_of_location = function
  | `Query    -> "query"
  | `Header   -> "header"
  | `Path     -> "path"
  | `FormData -> "formData"
  | `Body     -> "body"

let create ?(duplicate = false) ~reference_base ~reference_root (p : t) =
  let t =
    match p.location with
    | `Body ->
        Schema.create ~reference_base ~reference_root (some p.schema)
        |> Schema.to_string
    | _     ->
        kind_to_string p in
  let n =
    let n = name p.name in
    let loc = string_of_location p.location in
    if duplicate && n <> loc
    then sprintf "%s_%s" loc n
    else n in
  let descr = p.description in
  let create_sig, create_impl =
    if p.required then Val.Sig.named, Val.Impl.named
    else Val.Sig.optional, Val.Impl.optional in
  (create_sig ?descr n t, create_impl n t ~origin:(Val.Impl.origin p))