Skip to content

WIP json:api helpers #240

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions lib/open_api_spex/cast_parameters.ex
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,18 @@ defmodule OpenApiSpex.CastParameters do
end

defp cast_location(location, schema, components, conn) do
IO.inspect(conn, label: "conn")
IO.inspect({location, schema}, label: "casting {location, schema}")

params =
get_params_by_location(
conn,
location,
schema.properties |> Map.keys() |> Enum.map(&Atom.to_string/1)
)

IO.inspect(params, label: "params")

ctx = %Cast{
value: params,
schema: schema,
Expand Down
39 changes: 39 additions & 0 deletions lib/open_api_spex/json_api_helpers.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
defmodule OpenApiSpex.JsonApiHelpers do
alias OpenApiSpex.JsonApiHelpers.{JsonApiDocument, JsonApiResource}

def document_schema(document) do
JsonApiDocument.schema(document)
end

def resource_schema(resource) do
JsonApiResource.schema(resource)
end

defmacro generate_document_schema(attrs) do
quote do
require OpenApiSpex

@document struct!(JsonApiDocument, unquote(attrs))
def document, do: @document

@document_schema JsonApiDocument.schema(@document)
def document_schema, do: @document_schema

OpenApiSpex.schema(@document_schema)
end
end

defmacro generate_resource_schema(attrs) do
quote do
require OpenApiSpex

@resource struct!(JsonApiResource, unquote(attrs))
def resource, do: @resource

@resource_schema JsonApiResource.schema(@resource)
def resource_schema, do: @resource_schema

OpenApiSpex.schema(@resource_schema)
end
end
end
51 changes: 51 additions & 0 deletions lib/open_api_spex/json_api_helpers/json_api_document.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
defmodule OpenApiSpex.JsonApiHelpers.JsonApiDocument do
alias OpenApiSpex.Schema
alias OpenApiSpex.JsonApiHelpers.JsonApiResource

defstruct resource: nil,
multiple: false,
title: nil,
"x-struct": nil

def schema(%__MODULE__{} = document) do
if not is_binary(document.title) do
raise "%JsonApiDocument{} :title is required and must be a string"
end

resource = document.resource
resource_item_schema = JsonApiResource.schema(resource)

resource_title =
case resource_item_schema do
%Schema{} = schema -> schema.title
module when is_atom(module) and not is_nil(module) -> module.schema().title
end

resource_schema =
if document.multiple do
%Schema{
type: :array,
items: resource_item_schema,
title: resource_title <> "List"
}
else
resource_item_schema
end

%Schema{
type: :object,
properties: %{
data: resource_schema
},
required: [:data],
title: document.title,
"x-struct": document."x-struct"
}
end

def schema(document_attrs) when is_list(document_attrs) or is_map(document_attrs) do
__MODULE__
|> struct!(document_attrs)
|> schema()
end
end
41 changes: 41 additions & 0 deletions lib/open_api_spex/json_api_helpers/json_api_resource.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
defmodule OpenApiSpex.JsonApiHelpers.JsonApiResource do
alias OpenApiSpex.Schema

defstruct additionalProperties: nil,
properties: %{},
required: [],
title: nil

def schema(resource) when is_atom(resource) and not is_nil(resource) do
resource.schema()."x-struct"
end

def schema(%__MODULE__{} = resource) do
if not is_binary(resource.title) do
raise "%JsonApiResource{} :title is required and must be a string"
end

%Schema{
type: :object,
properties: %{
id: %Schema{type: :string},
type: %Schema{type: :string},
attributes: attributes_schema(resource)
},
required: [:id, :type],
title: resource.title <> "Resource"
}
end

def attributes_schema(%__MODULE__{} = resource) do
if not is_binary(resource.title) do
raise "%JsonApiResource{} :title is required and must be a string"
end

%Schema{
type: :object,
properties: resource.properties,
title: resource.title <> "Attributes"
}
end
end
13 changes: 12 additions & 1 deletion lib/open_api_spex/schema_resolver.ex
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ defmodule OpenApiSpex.SchemaResolver do
{paths, schemas} = resolve_schema_modules_from_paths(spec.paths, schemas)
schemas = resolve_schema_modules_from_schemas(schemas)
{responses, _} = resolve_schema_modules_from_responses(responses, schemas)
%{spec | paths: paths, components: %{components| schemas: schemas, responses: responses}}
%{spec | paths: paths, components: %{components | schemas: schemas, responses: responses}}
end

defp resolve_schema_modules_from_paths(paths = %{}, schemas = %{}) do
Expand Down Expand Up @@ -217,6 +217,17 @@ defmodule OpenApiSpex.SchemaResolver do
properties: properties
}

IO.inspect(schema, label: "schema")

# title = schema.title

# schemas =
# case {title, schemas} do
# {nil, _} -> schemas
# {_, %{^title => _}} -> schemas
# _ -> Map.put(schemas, title, schema)
# end

{schema, schemas}
end

Expand Down
27 changes: 20 additions & 7 deletions test/cast_parameters_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -35,26 +35,39 @@ defmodule OpenApiSpex.CastParametersTest do
{:ok, conn} = CastParameters.cast(conn, operation, components)
assert %{params: %{includeInactive: false}} = conn
end

# test "params are validated" do
# conn = create_conn(query_string: "/invalid")
# operation = create_operation()
# components = create_empty_components()
# {:error, error} = CastParameters.cast(conn, operation, components)
# assert error == :error
# end

test "path params are validated" do
end
end

defp create_conn() do
defp create_conn(opts \\ []) do
opts = Map.new(opts)
query_string = opts[:query_string]

:get
|> Plug.Test.conn("/api/users/")
|> Plug.Test.conn("/api/users#{query_string}")
|> Plug.Conn.put_req_header("content-type", "application/json")
|> Plug.Conn.fetch_query_params()
end

defp create_conn_with_unexpected_path_param() do
:get
|> Plug.Test.conn("/api/users?invalid_key=value")
|> Plug.Conn.put_req_header("content-type", "application/json")
|> Plug.Conn.fetch_query_params()
create_conn(query_string: "?invalid_key=value")
end

defp create_operation() do
%Operation{
parameters: [
Operation.parameter(:id, :query, :string, "User ID", example: "1"),
Operation.parameter(:id, :path, %Schema{type: :string, pattern: ~r/^\d+$/}, "User ID",
example: "1"
),
Operation.parameter(
:includeInactive,
:query,
Expand Down
10 changes: 5 additions & 5 deletions test/controller_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,14 @@ defmodule OpenApiSpex.ControllerTest do

test "has no docs when false" do
assert capture_io(:stderr, fn ->
refute @controller.open_api_operation(:skip_this_doc)
end) == ""
refute @controller.open_api_operation(:skip_this_doc)
end) == ""
end

test "prints warn when no @doc specified" do
assert capture_io(:stderr, fn ->
refute @controller.open_api_operation(:no_doc_specified)
end) =~ ~r/warning:/
refute @controller.open_api_operation(:no_doc_specified)
end) =~ ~r/warning:/
end
end

Expand All @@ -96,7 +96,7 @@ defmodule OpenApiSpex.ControllerTest do
end

test "fails on both type and schema specified" do
assert_raise ArgumentError, ~r/Both :type and :schema options were specified/, fn ->
assert_raise ArgumentError, ~r/Both :type and :schema options were specified/, fn ->
@controller.open_api_operation(:non_exlusive_paramter_type_schema_docs)
end
end
Expand Down
82 changes: 82 additions & 0 deletions test/json_api_helpers_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
defmodule OpenApiSpex.JsonApiHelpersTest do
use ExUnit.Case, async: true

alias OpenApiSpexTest.{CartDocument, CartIndexDocument, CartResource}
alias OpenApiSpex.{JsonApiHelpers, Schema}
alias OpenApiSpex.JsonApiHelpers.JsonApiResource

describe "from operation specs" do
test "index action" do
spec = OpenApiSpexTest.ApiSpec2.spec()
assert %Schema{} = _schema = spec.components.schemas["CartIndexResponse"]
end
end

describe "generate_resource_document/1" do
test "generate schema/0" do
assert %Schema{} = schema = CartDocument.schema()
assert schema.title == "CartDocument"
assert %{data: _} = schema.properties
assert schema.properties.data.title == CartResource.schema().title
end

test "generate schema for index document" do
assert %Schema{} = schema = CartIndexDocument.schema()
assert schema.title == "CartIndexDocument"
assert %{data: _} = schema.properties
assert schema.properties.data.type == :array
assert schema.properties.data.items == OpenApiSpexTest.CartResource
end
end

describe "generate_resource_schema/1" do
test "generate resource/0 and resource_schema/0" do
assert %JsonApiResource{} = CartResource.resource()
assert %Schema{} = schema = CartResource.schema()
assert schema.title == "CartResource"
end
end

describe "resource_schema/1" do
test "attributes" do
resource = CartResource.resource()
schema = JsonApiHelpers.resource_schema(resource)
assert schema.properties.attributes == JsonApiResource.attributes_schema(resource)
assert %Schema{} = schema.properties.id
assert %Schema{} = schema.properties.type
end

test "title" do
resource = CartResource.resource()
schema = JsonApiHelpers.resource_schema(resource)
assert schema.title == "CartResource"
end
end

describe "attributes_schema/1" do
test "generates schema with same properties" do
resource = CartResource.resource()
schema = JsonApiResource.attributes_schema(resource)
assert schema.properties == resource.properties
end

test "generates title" do
resource = CartResource.resource()
schema = JsonApiResource.attributes_schema(resource)
assert schema.title == "CartAttributes"
end

test ":title must be a string" do
resource = CartResource.resource()
resource = %{resource | title: nil}

assert_raise(
RuntimeError,
"%JsonApiResource{} :title is required and must be a string",
fn ->
JsonApiResource.attributes_schema(resource)
end
)
end
end
end
4 changes: 2 additions & 2 deletions test/support/api_spec.ex
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ defmodule OpenApiSpexTest.ApiSpec do
},
components: %Components{
schemas:
for schemaMod <- [
for schema_mod <- [
Schemas.Pet,
Schemas.PetType,
Schemas.Cat,
Expand All @@ -35,7 +35,7 @@ defmodule OpenApiSpexTest.ApiSpec do
Schemas.Primitive
],
into: %{} do
schema = schemaMod.schema()
schema = schema_mod.schema()
{schema.title, schema}
end
},
Expand Down
30 changes: 30 additions & 0 deletions test/support/api_spec_2.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
defmodule OpenApiSpexTest.ApiSpec2 do
alias OpenApiSpex.{OpenApi, Contact, License, Paths, Server, Info}
alias OpenApiSpexTest.Router2

@behaviour OpenApi

@impl OpenApi
def spec() do
%OpenApi{
servers: [
%Server{url: "http://example.com"}
],
info: %Info{
title: "A",
version: "3.0",
contact: %Contact{
name: "joe",
email: "[email protected]",
url: "https://help.joe.com"
},
license: %License{
name: "MIT",
url: "http://mit.edu/license"
}
},
paths: Paths.from_router(Router2)
}
|> OpenApiSpex.resolve_schema_modules()
end
end
11 changes: 11 additions & 0 deletions test/support/cart_document.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
defmodule OpenApiSpexTest.CartDocument do
alias OpenApiSpex.JsonApiHelpers
alias OpenApiSpexTest.CartResource

require OpenApiSpex.JsonApiHelpers

JsonApiHelpers.generate_document_schema(
title: "CartDocument",
resource: CartResource.resource()
)
end
Loading