Some More Routes
Learn how to implement the routes for creating a new product and returning all products.
We'll cover the following...
Creating a new product
Let’s create a new product.
path("products") {post {entity(as[Product]) { p =>complete {repo.saveProduct(p)}}}}
Creating a product
As you can see, the function is basically the same as the one for updating a product, except we’re calling a different function from the repository.
Returning all products
Let’s now take a look at the “return all products” endpoint.
Press + to interact
path("products") {get {complete {val products = for {rows <- repo.loadProducts()ps <- Future {rows.toList.groupBy(_._1).map {case (_, cols) => Product.fromDatabase(cols)}}} yield psproducts.map(_.toList.flatten)}}}
This looks more complicated than the other endpoints. So, what exactly are we doing here? Well, first we load the raw product data from the repository (Line ). After that, we convert it into the proper data model — or into a list of product entities, to be more exact. What is wrong with that approach?
- Firstly, we are performing operations in memory. This is