2023-11-28 05:21:17 +13:00
# Getting Started With AshMoney
2023-11-28 05:25:15 +13:00
## Bring in the ash_graphql dependency
```elixir
def deps()
[
...
2023-12-05 10:19:39 +13:00
{:ash_money, "~> 0.1.2"}
2023-11-28 05:25:15 +13:00
]
end
```
## Setup
2023-11-28 05:21:17 +13:00
The primary thing that AshMoney provides is `AshMoney.Types.Money` . This is backed by `ex_money` . You can use it out of the box like so:
```elixir
attribute :balance, AshMoney.Types.Money
```
Or you can add it to your compile time list of types for easier reference:
```elixir
config :ash, :custom_types, money: AshMoney.Types.Money
```
Then compile ash again, `mix deps.compile ash --force` , and refer to it like so:
```elixir
attribute :balance, :money
```
## AshPostgres Support
2023-11-28 06:03:13 +13:00
Add the `:ex_money_sql` dependency to your `mix.exs` file.
2023-11-28 05:21:17 +13:00
Thanks to `ex_money_sql` , there are excellent tools for lowering support for money into your postgres database. This allows for things like aggregates that sum amounts, and referencing money in expressions:
```elixir
sum :sum_of_usd_balances, :accounts, :balance do
2023-11-28 07:11:14 +13:00
filter expr(
fragment("(?).currency_code", balance) == "USD"
)
2023-11-28 05:21:17 +13:00
end
```
To install it, add `AshMoney.AshPostgresExtension` to your list of `installed_extensions` in your repo, and generate migrations.
```elixir
defmodule YourRepo do
def installed_extensions do
[..., AshMoney.AshPostgresExtension]
end
end
```
## AshGraphql Support
Add the following to your schema file:
```elixir
object :money do
field(:amount, non_null(:decimal))
field(:currency, non_null(:string))
end
2023-11-28 12:49:01 +13:00
```
## Limitations
Support for using built in operators with data layers that don't support it. For example, `expr(money + money)` will work in `AshPostgres` , but not when using `Ash.DataLayer.Ets` .
We need to make built in functions extensible by type to make this work.