Skip to content
Permalink
Browse files
Code for step 3
  • Loading branch information
akoutmos committed Jun 29, 2020
1 parent 8a4ba14 commit ad5d6aad6cf092e71804bbf097b7ccf4122ae13b
Showing 3 changed files with 66 additions and 11 deletions.
@@ -0,0 +1,27 @@
defmodule BookStore.Books.Book do
use Ecto.Schema

import Ecto.Changeset

alias __MODULE__

@derive {Jason.Encoder, only: ~w(title authors description price quantity)a}
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "books" do
field :title, :string
field :authors, {:array, :string}
field :description, :string
field :price, :string
field :quantity, :integer

timestamps()
end

@doc false
def changeset(%Book{} = book, attrs) do
book
|> cast(attrs, ~w(title authors description price quantity)a)
|> validate_required(~w(title authors description quantity)a)
end
end
@@ -0,0 +1,16 @@
defmodule BookStore.Repo.Migrations.Books do
use Ecto.Migration

def change do
create table(:books, primary_key: false) do
add :id, :binary_id, primary_key: true
add :title, :string
add :authors, {:array, :string}
add :description, :text
add :price, :string
add :quantity, :integer

timestamps()
end
end
end
@@ -1,11 +1,23 @@
# Script for populating the database. You can run it as:
#
# mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
# BookStore.Repo.insert!(%BookStore.SomeSchema{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
alias BookStore.Books.Book
alias BookStore.Repo

{book_data, _} =
BookStore.ManningBookScraper.data_file_location()
|> Code.eval_file()

book_data
|> Enum.map(fn
%{price: :not_for_sale} = book ->
book
|> Map.put(:price, "N/A")
|> Map.put(:quantity, 0)

book ->
book
|> Map.put(:quantity, 5_000)
end)
|> Enum.each(fn book ->
%Book{}
|> Book.changeset(book)
|> Repo.insert()
end)

0 comments on commit ad5d6aa

Please sign in to comment.