33
44
55-export ([init /2 , handle /2 , terminate /3 ]).
6- -export ([routes /1 , load_schema /2 , choose_module / 0 ]).
6+ -export ([routes /1 , load_schema /2 ]).
77-export ([read_schema /1 ]).
88-export ([routes_sort /1 ]). % for tests
99
1414routes (#{schema := SchemaPath , module := Module , name := Name , prefix := Prefix } = Config ) ->
1515 #{} = Schema = load_schema (SchemaPath , Name ),
1616 SchemaOpts = get_schema_opts (Config ),
17- HandlerModule = choose_module (),
18-
1917 #{paths := Paths } = Schema ,
2018 Routes = lists :map (fun ({Path ,PathSpec }) ->
2119 <<" /" , _ /binary >> = CowboyPath = re :replace (atom_to_list (Path ), " {([^\\ }]+)}" , " :\\ 1" ,[global ,{return ,binary }]),
@@ -27,23 +25,13 @@ routes(#{schema := SchemaPath, module := Module, name := Name, prefix := Prefix}
2725 % It is too bad to pass all this stuff through cowboy options because it starts suffering
2826 % from GC on big state. Either ETS, either persistent_term, either compilation of custom code
2927 persistent_term :put ({openapi_handler_route ,Name ,CowboyPath }, PathSpec1 #{name => Name , module => Module , schema_opts => SchemaOpts }),
30- {<<Prefix /binary , CowboyPath /binary >>, HandlerModule , {Name ,CowboyPath }}
28+ {<<Prefix /binary , CowboyPath /binary >>, ? MODULE , {Name ,CowboyPath }}
3129 end , maps :to_list (Paths )),
3230 % After sorting, bindings (starting with ":") must be after constant path segments, so generic routes only work after specific ones.
3331 % E.g. "/api/users/admin" must be before "/api/users/:id"
3432 % Thus special sorting function
3533 routes_sort (Routes ).
3634
37- choose_module () ->
38- try
39- % Check if cowboy uses modern Req (map)
40- 1234 = cowboy_req :port (#{port => 1234 }),
41- ? MODULE
42- catch
43- error :{badrecord ,_ }:_ ->
44- % cowboy uses record for Req, use legacy wrapper
45- openapi_handler_legacy
46- end .
4735
4836prepare_operation_fm (_M , #{operationId := OperationId_ } = Operation , Parameters ) ->
4937 Op1 = maps :remove (description ,Operation ),
@@ -540,7 +528,7 @@ terminate(_,_,_) ->
540528
541529get_schema_opts (#{schema_opts := #{} = SchemaOpts }) ->
542530 maps :map (fun
543- (extra_obj_key ,Flag ) when Flag == drop ; Flag == error ; Flag == pass -> ok ;
531+ (extra_obj_key ,Flag ) when Flag == drop ; Flag == error -> ok ;
544532 (K ,V ) -> error ({bad_schema_opt ,K ,V })
545533 end , SchemaOpts ),
546534 SchemaOpts ;
0 commit comments