package openapi_router

  1. Overview
  2. Docs

Source file router.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
open Core
open Base.Poly

let rewrite_path p =
  let components = String.split ~on:'/' p in
  let named_params =
    List.filter_map ~f:(String.chop_prefix ~prefix:"s") components
  in
  let max_anon =
    List.fold ~init:(-1) named_params ~f:(fun i s ->
        try Scanf.sscanf s "anon%d" (fun d -> if d > i then d else i)
        with Scanf.Scan_failure _ -> i)
  in
  let parse_component s =
    match String.chop_prefix ~prefix:":" s with
    | Some c -> `Named c
    | None -> if s = "*" || s = "**" then `Anon else `Match
  in
  let mk_param n =
    Spec.(make_parameter_object ~name:n ~in_:Path ~required:true ())
    |> Json_schema.Helpers.obj
  in
  List.fold
    ~init:([], [], max_anon + 1)
    components
    ~f:(fun (cs, ps, anon_count) c ->
      match parse_component c with
      | `Named c -> (("{" ^ c ^ "}") :: cs, mk_param c :: ps, anon_count)
      | `Anon ->
        let name = sprintf "anon%d" anon_count in
        (("{" ^ name ^ "}") :: cs, mk_param name :: ps, anon_count + 1)
      | `Match -> (c :: cs, ps, anon_count))
  |> function
  | cs, ps, _ -> (String.concat ~sep:"/" (List.rev cs), ps)

let merge_parameters orig add =
  let same_param (p1 : Spec.parameter_object Json_schema.or_ref)
      (p2 : Spec.parameter_object Json_schema.or_ref) =
    let open Json_schema in
    let open Spec in
    match (p1, p2) with
    | Ref r1, Ref r2 -> r1 = r2
    | Obj p1, Obj p2 -> p1.name = p2.name
    | _ -> false
  in
  List.fold_left ~init:orig add ~f:(fun orig p ->
      match List.find ~f:(same_param p) orig with
      | Some _ -> orig
      | None -> p :: orig)

module type Config_Type = sig
  type app
  type route
  type handler

  val json_path : string
  val doc_path : string
  val json_route : string -> route
  val doc_route : string -> route
  val get : string -> handler -> route
  val post : string -> handler -> route
  val delete : string -> handler -> route
  val put : string -> handler -> route
  val options : string -> handler -> route
  val head : string -> handler -> route
  val patch : string -> handler -> route
  val build_routes : route list -> app
end

module Make (Config : Config_Type) = struct
  type t = {
    spec : Spec.t;
    routes : Config.route list;
  }

  let empty =
    {
      spec =
        Spec.make ~openapi:"3.0.0"
          ~info:(Spec.make_info_object ~title:"Application" ~version:"0.1" ())
          ~paths:[] ();
      routes = [];
    }

  let title t r =
    { r with spec = { r.spec with info = { r.spec.info with title = t } } }

  let description d r =
    {
      r with
      spec = { r.spec with info = { r.spec.info with description = Some d } };
    }

  let terms_of_service t r =
    {
      r with
      spec =
        { r.spec with info = { r.spec.info with terms_of_service = Some t } };
    }

  let contact c r =
    {
      r with
      spec = { r.spec with info = { r.spec.info with contact = Some c } };
    }

  let license l r =
    {
      r with
      spec = { r.spec with info = { r.spec.info with license = Some l } };
    }

  let version v r =
    { r with spec = { r.spec with info = { r.spec.info with version = v } } }

  let schema n s a =
    let open Spec in
    Option.value ~default:(make_components_object ()) a.spec.components
    |> (fun cs ->
         Option.value ~default:[] cs.schemas |> fun ss ->
         { cs with schemas = Some ((n, s) :: ss) })
    |> Option.return
    |> fun cs -> { a with spec = { a.spec with components = cs } }

  let response n r a =
    let open Spec in
    Option.value ~default:(make_components_object ()) a.spec.components
    |> (fun cs ->
         Option.value ~default:[] cs.responses |> fun rs ->
         { cs with responses = Some ((n, r) :: rs) })
    |> Option.return
    |> fun cs -> { a with spec = { a.spec with components = cs } }

  let parameter n p a =
    let open Spec in
    Option.value ~default:(make_components_object ()) a.spec.components
    |> (fun cs ->
         Option.value ~default:[] cs.parameters |> fun ps ->
         { cs with parameters = Some ((n, p) :: ps) })
    |> Option.return
    |> fun cs -> { a with spec = { a.spec with components = cs } }

  let example n ex a =
    let open Spec in
    Option.value ~default:(make_components_object ()) a.spec.components
    |> (fun cs ->
         Option.value ~default:[] cs.examples |> fun ss ->
         { cs with examples = Some ((n, ex) :: ss) })
    |> Option.return
    |> fun cs -> { a with spec = { a.spec with components = cs } }

  let request_body n r a =
    let open Spec in
    Option.value ~default:(make_components_object ()) a.spec.components
    |> (fun cs ->
         Option.value ~default:[] cs.request_bodies |> fun ss ->
         { cs with request_bodies = Some ((n, r) :: ss) })
    |> Option.return
    |> fun cs -> { a with spec = { a.spec with components = cs } }

  let header n h a =
    let open Spec in
    Option.value ~default:(make_components_object ()) a.spec.components
    |> (fun cs ->
         Option.value ~default:[] cs.headers |> fun ss ->
         { cs with headers = Some ((n, h) :: ss) })
    |> Option.return
    |> fun cs -> { a with spec = { a.spec with components = cs } }

  let security_scheme n s a =
    let open Spec in
    Option.value ~default:(make_components_object ()) a.spec.components
    |> (fun cs ->
         Option.value ~default:[] cs.security_schemes |> fun ss ->
         { cs with security_schemes = Some ((n, s) :: ss) })
    |> Option.return
    |> fun cs -> { a with spec = { a.spec with components = cs } }

  let link n l a =
    let open Spec in
    Option.value ~default:(make_components_object ()) a.spec.components
    |> (fun cs ->
         Option.value ~default:[] cs.links |> fun ss ->
         { cs with links = Some ((n, l) :: ss) })
    |> Option.return
    |> fun cs -> { a with spec = { a.spec with components = cs } }

  let callback n c a =
    let open Spec in
    Option.value ~default:(make_components_object ()) a.spec.components
    |> (fun cs ->
         Option.value ~default:[] cs.callbacks |> fun ss ->
         { cs with callbacks = Some ((n, c) :: ss) })
    |> Option.return
    |> fun cs -> { a with spec = { a.spec with components = cs } }

  let schema_ref x = "#/components/schemas/" ^ x |> Json_schema.Helpers.ref
  let response_ref x = "#/components/responses/" ^ x |> Json_schema.Helpers.ref

  let parameter_ref x =
    "#/components/parameters/" ^ x |> Json_schema.Helpers.ref

  let example_ref x = "#/components/examples/" ^ x |> Json_schema.Helpers.ref

  let request_body_ref x =
    "#/components/requestBodies/" ^ x |> Json_schema.Helpers.ref

  let header_ref x = "#/components/headers/" ^ x |> Json_schema.Helpers.ref

  let security_scheme_ref x =
    "#/components/securitySchemes/" ^ x |> Json_schema.Helpers.ref

  let link_ref x = "#/components/link/" ^ x |> Json_schema.Helpers.ref
  let callback_ref x = "#/components/callbacks/" ^ x |> Json_schema.Helpers.ref

  let get ?tags ?summary ?description ?external_docs ?operation_id
      ?(parameters = []) ?request_body ?(responses = []) ?callbacks ?deprecated
      ?security ?servers path handler a =
    let orig_path = path in
    let path, pathps = rewrite_path path in
    let p =
      List.Assoc.find ~equal:( = ) a.spec.paths path
      |> Option.value ~default:(Spec.make_path_object ())
    in
    let p =
      {
        p with
        get =
          Some
            (Spec.make_operation_object ?tags ?summary ?description
               ?external_docs ?operation_id
               ~parameters:(merge_parameters parameters pathps)
               ?request_body ~responses ?callbacks ?deprecated ?security
               ?servers ());
      }
    in
    let paths = List.Assoc.add ~equal:( = ) a.spec.paths path p in
    {
      spec = { a.spec with paths };
      routes = a.routes @ [Config.get orig_path handler];
    }

  let default_request_body =
    let open Json_schema in
    let open Spec in
    let mt = make_media_type_object ~schema:(Obj (make_schema ())) () in
    Spec.make_request_body_object ~content:[("text/plain", mt)] () |> fun o ->
    Obj o

  let post ?tags ?summary ?description ?external_docs ?operation_id
      ?(parameters = []) ?request_body ?(responses = []) ?callbacks ?deprecated
      ?security ?servers path handler a =
    let orig_path = path in
    let path, pathps = rewrite_path path in
    let p =
      List.Assoc.find ~equal:( = ) a.spec.paths path
      |> Option.value ~default:(Spec.make_path_object ())
    in
    let p =
      {
        p with
        post =
          Some
            (Spec.make_operation_object ?tags ?summary ?description
               ?external_docs ?operation_id
               ~parameters:(merge_parameters parameters pathps)
               ~request_body:
                 (Option.value request_body ~default:default_request_body)
               ~responses ?callbacks ?deprecated ?security ?servers ());
      }
    in
    let paths = List.Assoc.add ~equal:( = ) a.spec.paths path p in
    {
      spec = { a.spec with paths };
      routes = a.routes @ [Config.post orig_path handler];
    }

  let delete ?tags ?summary ?description ?external_docs ?operation_id
      ?(parameters = []) ?request_body ?(responses = []) ?callbacks ?deprecated
      ?security ?servers path handler a =
    let orig_path = path in
    let path, pathps = rewrite_path path in
    let p =
      List.Assoc.find ~equal:( = ) a.spec.paths path
      |> Option.value ~default:(Spec.make_path_object ())
    in
    let p =
      {
        p with
        delete =
          Some
            (Spec.make_operation_object ?tags ?summary ?description
               ?external_docs ?operation_id
               ~parameters:(merge_parameters parameters pathps)
               ?request_body ~responses ?callbacks ?deprecated ?security
               ?servers ());
      }
    in
    let paths = List.Assoc.add ~equal:( = ) a.spec.paths path p in
    {
      spec = { a.spec with paths };
      routes = a.routes @ [Config.delete orig_path handler];
    }

  let put ?tags ?summary ?description ?external_docs ?operation_id
      ?(parameters = []) ?request_body ?(responses = []) ?callbacks ?deprecated
      ?security ?servers path handler a =
    let orig_path = path in
    let path, pathps = rewrite_path path in
    let p =
      List.Assoc.find ~equal:( = ) a.spec.paths path
      |> Option.value ~default:(Spec.make_path_object ())
    in
    let p =
      {
        p with
        put =
          Some
            (Spec.make_operation_object ?tags ?summary ?description
               ?external_docs ?operation_id
               ~parameters:(merge_parameters parameters pathps)
               ~request_body:
                 (Option.value request_body ~default:default_request_body)
               ~responses ?callbacks ?deprecated ?security ?servers ());
      }
    in
    let paths = List.Assoc.add ~equal:( = ) a.spec.paths path p in
    {
      spec = { a.spec with paths };
      routes = a.routes @ [Config.put orig_path handler];
    }

  let options ?tags ?summary ?description ?external_docs ?operation_id
      ?(parameters = []) ?request_body ?(responses = []) ?callbacks ?deprecated
      ?security ?servers path handler a =
    let orig_path = path in
    let path, pathps = rewrite_path path in
    let p =
      List.Assoc.find ~equal:( = ) a.spec.paths path
      |> Option.value ~default:(Spec.make_path_object ())
    in
    let p =
      {
        p with
        options =
          Some
            (Spec.make_operation_object ?tags ?summary ?description
               ?external_docs ?operation_id
               ~parameters:(merge_parameters parameters pathps)
               ?request_body ~responses ?callbacks ?deprecated ?security
               ?servers ());
      }
    in
    let paths = List.Assoc.add ~equal:( = ) a.spec.paths path p in
    {
      spec = { a.spec with paths };
      routes = a.routes @ [Config.options orig_path handler];
    }

  let head ?tags ?summary ?description ?external_docs ?operation_id
      ?(parameters = []) ?request_body ?(responses = []) ?callbacks ?deprecated
      ?security ?servers path handler a =
    let orig_path = path in
    let path, pathps = rewrite_path path in
    let p =
      List.Assoc.find ~equal:( = ) a.spec.paths path
      |> Option.value ~default:(Spec.make_path_object ())
    in
    let p =
      {
        p with
        head =
          Some
            (Spec.make_operation_object ?tags ?summary ?description
               ?external_docs ?operation_id
               ~parameters:(merge_parameters parameters pathps)
               ?request_body ~responses ?callbacks ?deprecated ?security
               ?servers ());
      }
    in
    let paths = List.Assoc.add ~equal:( = ) a.spec.paths path p in
    {
      spec = { a.spec with paths };
      routes = a.routes @ [Config.head orig_path handler];
    }

  let patch ?tags ?summary ?description ?external_docs ?operation_id
      ?(parameters = []) ?request_body ?(responses = []) ?callbacks ?deprecated
      ?security ?servers path handler a =
    let orig_path = path in
    let path, pathps = rewrite_path path in
    let p =
      List.Assoc.find ~equal:( = ) a.spec.paths path
      |> Option.value ~default:(Spec.make_path_object ())
    in
    let p =
      {
        p with
        patch =
          Some
            (Spec.make_operation_object ?tags ?summary ?description
               ?external_docs ?operation_id
               ~parameters:(merge_parameters parameters pathps)
               ?request_body ~responses ?callbacks ?deprecated ?security
               ?servers ());
      }
    in
    let paths = List.Assoc.add ~equal:( = ) a.spec.paths path p in
    {
      spec = { a.spec with paths };
      routes = a.routes @ [Config.patch orig_path handler];
    }

  let build router =
    router.routes
    @ [
        Config.json_route (Spec.yojson_of_t router.spec |> Yojson.Safe.to_string);
        Config.doc_route
          (Printf.sprintf
             {|<html>
  <head>
    <title>Swagger %s UI</title>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui.css"
    />
    <link
      rel="shortcut icon"
      href="https://fastapi.tiangolo.com/img/favicon.png"
    />
  </head>
  <body>
    <div id="swagger-ui"></div>
    <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
    <script>
      const ui = SwaggerUIBundle({
        url: "%s",
        oauth2RedirectUrl: window.location.origin + "%s/oauth2-redirect",
        dom_id: "#swagger-ui",
        presets: [
          SwaggerUIBundle.presets.apis,
          SwaggerUIBundle.SwaggerUIStandalonePreset,
        ],
        layout: "BaseLayout",
        deepLinking: true,
        showExtensions: true,
        showCommonExtensions: true,
      });
    </script>
  </body>
</html>
|}
             router.spec.info.title Config.json_path Config.doc_path);
      ]
    |> Config.build_routes
end