はい!今やってます!

Work Pertly, Live Idly

Phoenix × Elixir ×MariaDB × Dockerでjsonを返すAPIを開発する (4日目 : DB設定 & API作成編)

前回の記事(Phoenix × ElixirでAPIを開発する (3日目 : DB環境構築編) - はい!今やってます!)に引き続きDBの設定をして、いよいよAPIを作成します。

MariaDBの権限付与

hostname -i //On API Container
grant all privileges on *.* to root@'172.%';
flush privileges;
SET PASSWORD FOR 'root'@'172.%' = PASSWORD('password');

phoenixのDB定義を設定

cd ${App_Dir}
vi config/dev.exs
設定例 DEV用)
config :api, Api.Repo,
adapter: Ecto.Adapters.MySQL,
username: "${User_Name}",
password: "${Password}",
database: "api_dev",
hostname: "mariadbmaster",

※テスト用も同様に書き換えてください。

DB設定

//APIサーバで
cd ${App_Path}
mix do deps.get, compile
mix ecto.create
env MIX_ENV=test mix ecto.create

jsonAPI作成

mix phoenix.gen.json Pool pools pool_name:string pool_url:string receiver_count:integer mayer_id:integer pool_rank:integer

ルーティング設定変更

vi web/router.ex
変更前)
  # Other scopes may use custom stacks.
  # scope "/api", Api do
  #   pipe_through :api
  # end
変更後)
  # Other scopes may use custom stacks.
  scope "/api", Api do
    pipe_through :api
    resources "/pools", PoolController, except: [:new, :edit]
  end

migration実行

mix ecto.migrate

ルーティングを確認

mix phoenix.routes

サーバを起動

mix phoenix.server

Postでレコード作成

curl -H "Content-Type: application/json" -X POST -d '{"pool": {"pool_name": "Test Resource", "pool_url": "http://www.test.com", "receiver_count": "0", "mayer_id": "999999999", "pool_rank": "1"}}' http://192.168.59.103:8080/api/pools

レコード確認

http://192.168.59.103:8080/api/pools

githubで新規リポジトリを作成してコミット

GitHub · Where software is built -> Create Repo

cd ${App Dir}
git init
git remote add origin https://github.com/uedayuji/api.git
git add .
git commit -m "Initial Commit"
git branch
git push origin master
git checkout -b release //Release Branch作成
git push origin release
git checkout -b develop
git push origin develop //Develop Branch作成

今回作成したコードはこちら(uedayuji/api · GitHub)で公開しています。 今後の実装はGithub上での開発となるので、このシリーズは完結です。