Skip to content

Commit

Permalink
feat: cache built specs with module hash
Browse files Browse the repository at this point in the history
This allows code to be automatically reloaded on code update enabling
hot code reload in development and in releases.

Close open-api-spex#72
  • Loading branch information
hauleth committed Jan 3, 2019
1 parent 49a8d39 commit 7d28d43
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions lib/open_api_spex/plug/put_api_spec.ex
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,7 @@ defmodule OpenApiSpex.Plug.PutApiSpec do

@impl Plug
def call(conn, module: mod) do
{spec, operation_lookup} =
case Application.get_env(:open_api_spex, mod) do
nil -> build_spec(mod)
cached -> cached
end
{spec, operation_lookup} = lookup(mod)

private_data =
conn
Expand All @@ -31,11 +27,23 @@ defmodule OpenApiSpex.Plug.PutApiSpec do
Plug.Conn.put_private(conn, :open_api_spex, private_data)
end

@spec build_spec(module) :: {OpenApiSpex.OpenApi.t, %{String.t => OpenApiSpex.Operation.t}}
defp build_spec(mod) do
@spec lookup(module) :: {OpenApiSpex.OpenApi.t, %{String.t => OpenApiSpex.Operation.t}}
defp lookup(mod) do
hash = mod.module_info(:md5)

case Application.get_env(:open_api_spex, mod) do
{^hash, spec, operation_lookup} -> {spec, operation_lookup}
_ -> build_spec(mod, hash)
end
end

@spec build_spec(module, binary()) :: {OpenApiSpex.OpenApi.t, %{String.t => OpenApiSpex.Operation.t}}
defp build_spec(mod, hash) do
spec = mod.spec()
operation_lookup = build_operation_lookup(spec)
Application.put_env(:open_api_spex, mod, {spec, operation_lookup})

Application.put_env(:open_api_spex, mod, {hash, spec, operation_lookup})

{spec, operation_lookup}
end

Expand All @@ -48,4 +56,4 @@ defmodule OpenApiSpex.Plug.PutApiSpec do
|> Stream.map(fn operation -> {operation.operationId, operation} end)
|> Enum.into(%{})
end
end
end

0 comments on commit 7d28d43

Please sign in to comment.