Skip to content

Commit 29c2e9e

Browse files
committed
[add] code from part 0 to part 5
0 parents  commit 29c2e9e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

65 files changed

+2149
-0
lines changed

.formatter.exs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
[
2+
import_deps: [:ecto, :phoenix],
3+
inputs: ["*.{ex,exs}", "priv/*/seeds.exs", "{config,lib,test}/**/*.{ex,exs}"],
4+
subdirectories: ["priv/*/migrations"]
5+
]

.gitignore

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# The directory Mix will write compiled artifacts to.
2+
/_build/
3+
4+
# If you run "mix test --cover", coverage assets end up here.
5+
/cover/
6+
7+
# The directory Mix downloads your dependencies sources to.
8+
/deps/
9+
10+
# Where 3rd-party dependencies like ExDoc output generated docs.
11+
/doc/
12+
13+
# Ignore .fetch files in case you like to edit your project deps locally.
14+
/.fetch
15+
16+
# If the VM crashes, it generates a dump, let's ignore it too.
17+
erl_crash.dump
18+
19+
# Also ignore archive artifacts (built via "mix archive.build").
20+
*.ez
21+
22+
# Ignore package tarball (built via "mix hex.build").
23+
bank_api-*.tar
24+
25+
# Since we are building assets from assets/,
26+
# we ignore priv/static. You may want to comment
27+
# this depending on your deployment strategy.
28+
/priv/static/

README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# BankAPI
2+
3+
To start your Phoenix server:
4+
5+
* Install dependencies with `mix deps.get`
6+
* Create and migrate your database with `mix ecto.setup`
7+
* Start Phoenix endpoint with `mix phx.server`
8+
9+
Now you can visit [`localhost:4000`](http://localhost:4000) from your browser.
10+
11+
Ready to run in production? Please [check our deployment guides](https://hexdocs.pm/phoenix/deployment.html).
12+
13+
## Learn more
14+
15+
* Official website: https://www.phoenixframework.org/
16+
* Guides: https://hexdocs.pm/phoenix/overview.html
17+
* Docs: https://hexdocs.pm/phoenix
18+
* Forum: https://elixirforum.com/c/phoenix-forum
19+
* Source: https://github.com/phoenixframework/phoenix

config/config.exs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# This file is responsible for configuring your application
2+
# and its dependencies with the aid of the Mix.Config module.
3+
#
4+
# This configuration file is loaded before any dependency and
5+
# is restricted to this project.
6+
7+
# General application configuration
8+
use Mix.Config
9+
10+
config :bank_api,
11+
namespace: BankAPI,
12+
ecto_repos: [BankAPI.Repo]
13+
14+
# Configures the endpoint
15+
config :bank_api, BankAPIWeb.Endpoint,
16+
url: [host: "localhost"],
17+
secret_key_base: "WSEiTWVZkM+GvZH2yzDbSQMvqD9HwFrKoLRDhH2OcyVDDcAxDe3IJznYI3RThTqp",
18+
render_errors: [view: BankAPIWeb.ErrorView, accepts: ~w(json), layout: false],
19+
pubsub_server: BankAPI.PubSub,
20+
live_view: [signing_salt: "ivJ8OM2T"]
21+
22+
# Configures Elixir's Logger
23+
config :logger, :console,
24+
format: "$time $metadata[$level] $message\n",
25+
metadata: [:request_id]
26+
27+
# Use Jason for JSON parsing in Phoenix
28+
config :phoenix, :json_library, Jason
29+
30+
# Configuring event store for Commanded that implement CQRS/ES
31+
config :bank_api, event_stores: [BankAPI.EventStore]
32+
config :bank_api, BankAPI.EventStore, serializer: Commanded.Serialization.JsonSerializer
33+
34+
# Import environment specific config. This must remain at the bottom
35+
# of this file so it overrides the configuration defined above.
36+
import_config "#{Mix.env()}.exs"

config/dev.exs

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
use Mix.Config
2+
3+
# Configure your database
4+
config :bank_api, BankAPI.Repo,
5+
username: "postgres",
6+
password: "postgres",
7+
database: "bank_api_dev",
8+
hostname: "localhost",
9+
show_sensitive_data_on_connection_error: true,
10+
pool_size: 10
11+
12+
config :bank_api, BankAPI.EventStore,
13+
serializer: Commanded.Serialization.JsonSerializer,
14+
types: EventStore.PostgresTypes,
15+
username: "postgres",
16+
password: "postgres",
17+
database: "bank_api_eventstore_dev",
18+
hostname: "localhost",
19+
pool_size: 10
20+
21+
# For development, we disable any cache and enable
22+
# debugging and code reloading.
23+
#
24+
# The watchers configuration can be used to run external
25+
# watchers to your application. For example, we use it
26+
# with webpack to recompile .js and .css sources.
27+
config :bank_api, BankAPIWeb.Endpoint,
28+
http: [port: 4000],
29+
debug_errors: true,
30+
code_reloader: true,
31+
check_origin: false,
32+
watchers: []
33+
34+
# ## SSL Support
35+
#
36+
# In order to use HTTPS in development, a self-signed
37+
# certificate can be generated by running the following
38+
# Mix task:
39+
#
40+
# mix phx.gen.cert
41+
#
42+
# Note that this task requires Erlang/OTP 20 or later.
43+
# Run `mix help phx.gen.cert` for more information.
44+
#
45+
# The `http:` config above can be replaced with:
46+
#
47+
# https: [
48+
# port: 4001,
49+
# cipher_suite: :strong,
50+
# keyfile: "priv/cert/selfsigned_key.pem",
51+
# certfile: "priv/cert/selfsigned.pem"
52+
# ],
53+
#
54+
# If desired, both `http:` and `https:` keys can be
55+
# configured to run both http and https servers on
56+
# different ports.
57+
58+
# Do not include metadata nor timestamps in development logs
59+
config :logger, :console, format: "[$level] $message\n"
60+
61+
# Set a higher stacktrace during development. Avoid configuring such
62+
# in production as building large stacktraces may be expensive.
63+
config :phoenix, :stacktrace_depth, 20
64+
65+
# Initialize plugs at runtime for faster development compilation
66+
config :phoenix, :plug_init_mode, :runtime

config/prod.exs

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
use Mix.Config
2+
3+
# For production, don't forget to configure the url host
4+
# to something meaningful, Phoenix uses this information
5+
# when generating URLs.
6+
#
7+
# Note we also include the path to a cache manifest
8+
# containing the digested version of static files. This
9+
# manifest is generated by the `mix phx.digest` task,
10+
# which you should run after static files are built and
11+
# before starting your production server.
12+
config :bank_api, BankAPIWeb.Endpoint,
13+
url: [host: "example.com", port: 80],
14+
cache_static_manifest: "priv/static/cache_manifest.json"
15+
16+
# Do not print debug messages in production
17+
config :logger, level: :info
18+
19+
# ## SSL Support
20+
#
21+
# To get SSL working, you will need to add the `https` key
22+
# to the previous section and set your `:url` port to 443:
23+
#
24+
# config :bank_api, BankAPIWeb.Endpoint,
25+
# ...
26+
# url: [host: "example.com", port: 443],
27+
# https: [
28+
# port: 443,
29+
# cipher_suite: :strong,
30+
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
31+
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH"),
32+
# transport_options: [socket_opts: [:inet6]]
33+
# ]
34+
#
35+
# The `cipher_suite` is set to `:strong` to support only the
36+
# latest and more secure SSL ciphers. This means old browsers
37+
# and clients may not be supported. You can set it to
38+
# `:compatible` for wider support.
39+
#
40+
# `:keyfile` and `:certfile` expect an absolute path to the key
41+
# and cert in disk or a relative path inside priv, for example
42+
# "priv/ssl/server.key". For all supported SSL configuration
43+
# options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1
44+
#
45+
# We also recommend setting `force_ssl` in your endpoint, ensuring
46+
# no data is ever sent via http, always redirecting to https:
47+
#
48+
# config :bank_api, BankAPIWeb.Endpoint,
49+
# force_ssl: [hsts: true]
50+
#
51+
# Check `Plug.SSL` for all available options in `force_ssl`.
52+
53+
# Finally import the config/prod.secret.exs which loads secrets
54+
# and configuration from environment variables.
55+
import_config "prod.secret.exs"

config/prod.secret.exs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# In this file, we load production configuration and secrets
2+
# from environment variables. You can also hardcode secrets,
3+
# although such is generally not recommended and you have to
4+
# remember to add this file to your .gitignore.
5+
use Mix.Config
6+
7+
database_url =
8+
System.get_env("DATABASE_URL") ||
9+
raise """
10+
environment variable DATABASE_URL is missing.
11+
For example: ecto://USER:PASS@HOST/DATABASE
12+
"""
13+
14+
config :bank_api, BankAPI.Repo,
15+
# ssl: true,
16+
url: database_url,
17+
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10")
18+
19+
secret_key_base =
20+
System.get_env("SECRET_KEY_BASE") ||
21+
raise """
22+
environment variable SECRET_KEY_BASE is missing.
23+
You can generate one by calling: mix phx.gen.secret
24+
"""
25+
26+
config :bank_api, BankAPIWeb.Endpoint,
27+
http: [
28+
port: String.to_integer(System.get_env("PORT") || "4000"),
29+
transport_options: [socket_opts: [:inet6]]
30+
],
31+
secret_key_base: secret_key_base
32+
33+
# ## Using releases (Elixir v1.9+)
34+
#
35+
# If you are doing OTP releases, you need to instruct Phoenix
36+
# to start each relevant endpoint:
37+
#
38+
# config :bank_api, BankAPIWeb.Endpoint, server: true
39+
#
40+
# Then you can assemble a release by calling `mix release`.
41+
# See `mix help release` for more information.

config/test.exs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
use Mix.Config
2+
3+
# Configure your database
4+
#
5+
# The MIX_TEST_PARTITION environment variable can be used
6+
# to provide built-in test partitioning in CI environment.
7+
# Run `mix help test` for more information.
8+
config :bank_api, BankAPI.Repo,
9+
username: "postgres",
10+
password: "postgres",
11+
database: "bank_api_test#{System.get_env("MIX_TEST_PARTITION")}",
12+
hostname: "localhost"
13+
14+
# We don't run a server during test. If one is required,
15+
# you can enable the server option below.
16+
config :bank_api, BankAPIWeb.Endpoint,
17+
http: [port: 4002],
18+
server: false
19+
20+
config :bank_api, :event_store,
21+
serializer: Commanded.Serialization.JsonSerializer,
22+
adapter: Commanded.EventStore.Adapters.InMemory
23+
24+
# config :commanded, event_store_adapter: Commanded.EventStore.Adapters.InMemory
25+
config :commanded, Commanded.EventStore.Adapters.InMemory,
26+
serializer: Commanded.Serialization.JsonSerializer,
27+
consistency: :strong
28+
29+
# Print only warnings and errors during test
30+
config :logger, level: :warn

lib/bank_api.ex

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
defmodule BankAPI do
2+
@moduledoc """
3+
BankAPI keeps the contexts that define your domain
4+
and business logic.
5+
6+
Contexts are also responsible for managing your data, regardless
7+
if it comes from the database, an external API or others.
8+
"""
9+
end

lib/bank_api/accounts.ex

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
defmodule BankAPI.Accounts do
2+
@moduledoc """
3+
The Accounts context
4+
"""
5+
alias BankAPI.Repo
6+
alias BankAPI.EventApp
7+
alias BankAPI.Accounts.Commands.{
8+
OpenAccount,
9+
CloseAccount,
10+
DepositIntoAccount,
11+
WithdrawFromAccount
12+
}
13+
alias BankAPI.Accounts.Projections.Account
14+
15+
import Ecto.Query, warn: false
16+
17+
def uuid_regex do
18+
~r/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/
19+
end
20+
21+
def get_account(id), do: Repo.get!(Account, id)
22+
23+
def close_account(id) do
24+
%CloseAccount{
25+
account_id: id
26+
}
27+
|> EventApp.dispatch()
28+
end
29+
30+
def deposit(id, amount) do
31+
dispatch_result = %DepositIntoAccount{
32+
account_id: id,
33+
deposit_amount: amount
34+
}
35+
|> EventApp.dispatch(consistency: :strong)
36+
37+
case dispatch_result do
38+
:ok ->
39+
{
40+
:ok,
41+
Repo.get!(Account, id)
42+
}
43+
44+
reply ->
45+
reply
46+
end
47+
end
48+
49+
def withdraw(id, amount) do
50+
dispatch_result =
51+
%WithdrawFromAccount{
52+
account_id: id,
53+
withdraw_amount: amount
54+
}
55+
|> EventApp.dispatch(consistency: :strong)
56+
57+
case dispatch_result do
58+
:ok -> {
59+
:ok,
60+
Repo.get!(Account, id)
61+
}
62+
63+
reply ->
64+
reply
65+
end
66+
end
67+
68+
def open_account(%{"initial_balance" => initial_balance}) do
69+
account_id = UUID.uuid4()
70+
71+
dispatch_result = %OpenAccount{
72+
initial_balance: initial_balance,
73+
account_id: account_id
74+
}
75+
|> EventApp.dispatch(consistency: :strong)
76+
77+
case dispatch_result do
78+
:ok ->
79+
{
80+
:ok,
81+
# get_account(account_id)
82+
%Account{
83+
id: account_id,
84+
current_balance: initial_balance,
85+
status: Account.status().open
86+
}
87+
}
88+
89+
reply ->
90+
reply
91+
end
92+
end
93+
94+
def open_account(_params), do: {:error, :bad_command}
95+
end

0 commit comments

Comments
 (0)