mschae / trailing_format_plug

An elixir plug to support legacy APIs that use a rails-like trailing format: http://api.dev/resources.json
25 stars 15 forks source link

Add the ability to constrain the formats checked. #17

Closed OvermindDL1 closed 7 years ago

OvermindDL1 commented 7 years ago

By default it acts the same way, however it adds in the ability to pass in a :valid option that takes a list or 1-arg function to test against, used like:

plug TrailingFormatPlug, valid: ["html", "xlsx", "csv"]

Or:

plug TrailingFormatPlug, valid: fn f -> is_valid_format(f) end

I've been using this in my internal project for a while now, figured it would be good to PR back. :-)

OvermindDL1 commented 7 years ago

For note, in my internal version I also have a helper function that takes a path (like from page_path(conn, blah)) and puts a .<format> in the proper place and returns the path. Unsure if that would be wanted to add to this or not as well so I left it out of my PR, but if it is wanted then I can PR it as well. It's pretty simple and is designed for standard phoenix paths.

mschae commented 7 years ago

Hey @OvermindDL1,

thanks for your contribution but I think this is out of the scope of this plug.

There is a possibility in Phoenix to negotiate formats, you can easily devise a plug yourself that accomplishes the same thing: https://hexdocs.pm/phoenix/Phoenix.Controller.html#accepts/2

Generally I try to keep these plugs as slim as possible as chaining them doesn't cause any overhead.

Hope that makes sense, thank you anyway!

OvermindDL1 commented 7 years ago

Actually the reason I used it was not to constrain the format types, but rather because a lot of my paths have periods . in them, so something like https://example.com/module/some.user.data get's turned into https://example.com/module/some.user, which entirely breaks things. It is not at all for replacing the Phoenix Controller's accepts plug as you still need it.

Technically this PR would not be useful if TrailingFormatPlug already used the accept information to determine what is valid, but as that plug can appear in the plug line 'after' the TrailingFormatPlug that is not easily possible.

In the case of not using this PR I'll still have to continue to use my fork unless you have some other idea of preventing it from breaking URL's with periods that are not formats?

And yes, in the above example something like https://example.com/module/some.user.data.json should indeed call https://example.com/module/some.user.data with format of "json" and json will never appear at the end of of their data line (technically I'm using json, xlsx, and csv formats).