Macro to inject plugs in controller

Hello! I’m developing a REST API using open_api_spex with an existing schema. Unfortunately but completely understandable, because of using an existing schema open_api_spex can’t map operation IDs to controller actions. What I can do is use multiple plug OpenApiSpex.Plug.CastAndValidate, [operation_id: <id from schema>] when action == :<controller action> to do the mapping. I’m trying to write a macro which takes a keyword list like [show: "get-resource", create: "create-resource"] and produces the longer mapping using plugs.

I tried the following but I get a compiler error because, of course, plug is an undefined function.

defmacro map_actions_to_ops(opts) do                              
  Enum.map(opts, fn {ac, op} ->                                   
    quote do                                                      
      plug OpenApiSpex.Plug.CastAndValidate,                      
           [json_render_error_v2: true, operation_id: unquote(op)]
           when var!(action) == unquote(ac)                       
    end                                                           
  end)                                                            
end                                                               

I believe there might be other mistakes. Is it possible to use macros accessible in the caller context? I can’t find a documentation on this.

1 Like