Skip to content

Instantly share code, notes, and snippets.

@aristotelesbr
Created June 6, 2020 15:48
Show Gist options
  • Select an option

  • Save aristotelesbr/67de5640da26bd8a1a6f9369550ec3eb to your computer and use it in GitHub Desktop.

Select an option

Save aristotelesbr/67de5640da26bd8a1a6f9369550ec3eb to your computer and use it in GitHub Desktop.

Revisions

  1. aristotelesbr created this gist Jun 6, 2020.
    15 changes: 15 additions & 0 deletions create_recipe.ex
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    defmodule RecipeBox.CreateRecipe do
    @moduledoc """
    Create a new Recipe
    """
    import Ecto.Changeset

    alias RecipeBox.{Recipe, Repo}

    def run(params) do
    %Recipe{}
    |> cast(params, [:title, :description, :quantity_people, :difficulty_level, :meal_id])
    |> validate_required([:title, :description])
    |> Repo.insert()
    end
    end
    20 changes: 20 additions & 0 deletions recipe_controller.ex
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    defmodule RecipeBoxWeb.RecipeController do
    use RecipeBoxWeb, :controller

    def create(conn, params) do
    case CreateRecipe.run(params) do
    {:ok, recipe} ->
    conn
    |> put_status(201)
    |> render("recipe.json", %{recipe: recipe})

    {:error, _} ->
    conn
    |> put_status(422)
    |> json(%{status: "unprocessable entity"})
    end
    end

    #...
    end

    21 changes: 21 additions & 0 deletions recipe_view.ex
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    defmodule RecipeBoxWeb.RecipeView do
    use RecipeBoxWeb, :view

    def render("recipe.json", %{recipe: recipe}) do
    %{
    id: recipe.id,
    title: recipe.title,
    description: recipe.description,
    difficulty_level: recipe.difficulty_level,
    quantity_people: recipe.quantity_people,
    meal: %{
    id: recipe.meal.id,
    title: recipe.meal.title,
    description: recipe.meal.description,
    active: recipe.meal.active,
    inserted_at: recipe.meal.inserted_at,
    updated_at: recipe.meal.updated_at
    }
    }
    end
    end