<turbo-stream action="append" target="posts_list"><template>    <div class="postbit" id="102004" data-post-id="102004">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="abitdodgy" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/abitdodgy/120/24328_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  abitdodgy
                    <span class="op-star" title="Thread Starter">
                      <img alt="OP" class="op-star-icon" src="/assets/thread-icons/thread-icon-thread-starter-df91e872.png" />
                    </span>
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>In the end, I stuck with my approach of having a Parser module pattern-match on the action name and delegate to the correct module for parsing. This way I only have to specify a parser once.</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">  def parse({:ok, %{body: xml, status_code: status} = resp}, action) when status in 200..299 do
    parsed_body = dispatch(xml, action)
    {:ok, %{resp | body: parsed_body}}
  end
  def parse(resp, _), do: resp

  @user_actions ~w[ListUsers GetUser]  # etc ...

  defp dispatch(xml, action) when action in @user_actions do
    User.parse(xml, action)
  end
</code></pre>
<p>I also realise that the API I wrote was contrived. A single generic <code>operation/2</code> function would have allowed me to interact with the entire IAM API without having to write a function for each IAM action/endpoint, as I was doing. It can be used by the internal API for convenience functions too.</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">  def operation(action, params, opts \\ []) do
    {parser, params} = Keyword.pop(params, :parser, &amp;Parser.parse/2)
    opts = Keyword.put_new(opts, :parser, parser)

    @shared_opts
    |&gt; Keyword.merge(params)
    |&gt; Keyword.put(:action, camelize(action))
    |&gt; list_to_camelized_map()
    |&gt; to_operation(opts)
  end

operation(:create_user, user_name: "foo")

# or for internal use

def create_user(username, opts \\ []) do
  operation([user_name: username] ++ opts)
end
</code></pre>
<p>Below is what I had until now. Those functions (<code>create_user/2</code>, <code>list_users</code>, etc…) are now relegated being to convenience functions only.</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">  def create_user(username, opts \\ []) do
    operation(:create_user, [user_name: username] ++ opts)
  end

  defp to_operation(params, opts) do
    %ExAws.Operation.Query{
      action: params["Action"],
      params: params,
      parser: Keyword.get(opts, :parser),
      path: params["Path"] || "/",
      service: :iam
    }
  end
</code></pre>
<p>So, what good are they? Well, maybe I can convert them to execute the operation on AWS instead of returning an ExAws op. For example:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">  def create_user(username, opts \\ []) do
    :create_user
    |&gt; operation([user_name: username] ++ opts)
    |&gt; ExAws.request()
    |&gt; to_user_struct()
  end
%User{
 arn: ...,
 create_date: ...,
 path: ...,
 user_name: ...,
 user_id: ...
}
</code></pre>
<p>Finally, it would be nice to have a parser for all those actions. But it’s hard work to write one for 60 or so actions. I wrote my first macro ever (be very afraid) to define DSL for parsers:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">  defparser(:get_user,
    fields: [
      get_user_result: [
        ~x"//GetUserResult",
        user: [
          ~x"./User",
          :path,
          :user_name,
          :arn,
          :user_id,
          :create_date
        ]
      ],
      response_metadata: [
        ~x"//ResponseMetadata",
        :request_id
      ]
    ]
  )
</code></pre>
<p>The macro itself, below, is still not optimal. I would rather do away with passing the XML paths (<code>~x"//GetUserResult"</code>) and handle that internally in the macro, but I have no way passing the type.</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule ExAws.Iam.TestMacro do
  import SweetXml, only: [sigil_x: 2]

  defmacro defparser(action, opts) do
    action_name = to_camel(action)

    fields =
      opts
      |&gt; Keyword.get(:fields)
      |&gt; Enum.map(fn field -&gt;
        compile(field)
      end)

    quote do
      def parse(xml, unquote(action_name)) do
        SweetXml.xpath(xml, ~x"//#{unquote(xml_path(action_name))}", [
          {
            unquote(xml_node(action_name)),
            [~x"//#{unquote(xml_path(action_name))}" | unquote(fields)]
          }
        ])
      end
    end
  end

  defp xml_path(action), do: action &lt;&gt; "Response"
  defp xml_node(action), do: xml_path(action) |&gt; to_snake()

  defp compile(field) when is_atom(field) do
    quote do
      {unquote(field), ~x"./#{unquote(to_camel(field))}/text()"s}
    end
  end

  defp compile({:sigil_x, _, _} = field), do: field

  defp compile({key, value}) do
    quote do
      {unquote(key), unquote(compile(value))}
    end
  end

  defp compile(list) when is_list(list) do
    Enum.map(list, fn field -&gt;
      compile(field)
    end)
  end

  defp to_camel(atom), do: atom |&gt; Atom.to_string() |&gt; Macro.camelize()
  defp to_snake(string), do: string |&gt; Macro.underscore() |&gt; String.to_atom()
end
</code></pre>
<p><a href="https://github.com/abitdodgy/ex_aws_iam/tree/macros" rel="noopener nofollow ugc">Here’s the code on a separate branch</a>.</p>
<p>Thoughts?</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="102004" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/better-design-pattern-for-creating-a-polymorphic-api/17390/12">Post #11</a>
	                </div>
	            </div>
              <div id="likers-container-102004" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="102004"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-most-liked cat-most-liked" title="One of the top 3 liked posts in this thread!"></div>
  </section>
</div>
</template></turbo-stream><turbo-stream action="replace" target="load-more-container"><template><div id="load-more-container" class="load-more-container">
    <span class="all-loaded">— All posts loaded —</span>
</div></template></turbo-stream>