Hi, I am teaching myself FP by porting a Rails 6 shopping app to Phoenix. Loving it so far!
I am muddling my way through the coding of an action to transform a list of products from the database, by adding a field (quantity added to the shopping cart) to each product.
Here’s what I’ve come up with so far:
def show(conn, _params) do
# TODO: create or find a 'cart'
products = Products.list_products() |> Enum.map(&product_with_quantity(cart, &1))
render(conn, "show.html", products: products, body_class: body_class)
end
defp product_with_quantity(%Carts.Cart{} = cart, %Products.Product{} = product) do
Product.as_map(product)
|> Map.put(:quantity_in_cart, Carts.count_cart_product_items(cart, product))
end
You’ll see that I have some code that converts a product’s Ecto struct into a map so that the cart quantity can be put into it. ‘as_map’ is a function in the Product schema module, which simply converts a struct to a map.
Ideally, I would like to do the mapping through a pipeline step and avoid the need for the private function, along the lines of:
Products.list_products()
|> Product.as_map()
|> Map.put(:quantity_in_cart, Carts.count_cart_product_items(cart, &1)
But this approach doesn’t seem to be possible due to my context function ‘count_cart_product_items’ expecting to receive a product struct, not a map. I realise that I could change the context function to expect a map instead of a struct but this would be inconsistent with the other context functions.
Would appreciate thoughts on how I might improve this code.
Thanks!
Lee.