Open7
REST APIからGraphQLのクエリを発行する
やること
https://http.cat から猫画像を取得し,GraphQL API のクエリを発行する.
Hasuraについて
Instant realtime GraphQL engine
GraphQLとSQL(JSON)を相互変換し,GraphQL APIサーバーを自動で構築するエンジン
参考
Formatter
https://prettier.io/docs/en/install.html に従い,プロジェクトにprettierを導入する.
npm install --save-dev --save-exact prettier
echo {}> .prettierrc.json
.prettierignore
を作成し,下記を追記.
# Ignore artifacts:
build
coverage
commit時にフォーマットする.
npm install --save-dev husky lint-staged
npx husky install
npm set-script prepare "husky install"
npx husky add .husky/pre-commit "npx lint-staged"
{
"lint-staged": {
"**/*": "prettier --write --ignore-unknown"
}
}
- DockerでHasuraを起動する
https://hasura.io/docs/latest/graphql/core/getting-started/docker-simple/
に従い,作業用ディレクトリにdocker-compose.yaml
を追加する
# in a new directory run
wget https://raw.githubusercontent.com/hasura/graphql-engine/stable/install-manifests/docker-compose/docker-compose.yaml
# or run
curl https://raw.githubusercontent.com/hasura/graphql-engine/stable/install-manifests/docker-compose/docker-compose.yaml -o docker-compose.yml
- Hasura GraphQL engineを起動し,URLからdatabaseにアクセスする
$ docker-compose up -d
http://localhost:8080/console
Data -> Manage -> Connect Database
にアクセス
Connect Database
をクリックし,データベースを作成する
Data -> Create table
からテーブルを作成する
Hasuraでは
1:n
の関係をArray relationship
1:1
の関係をObject relationship
と定義している
- APIからデータを取得し,Posgres内に格納する
Nodeのバージョンはv16.15.0
- 下記のようなテーブルに対し,各カラムに対応する情報 と,https://http.cat/ から取得した画像を
insert
する
- 下記を実行し,GraphQLのクエリを発行する
$node import_status.js
-
Data > status > Browse Rows
から正常にinsertされていることを確認
- graphiQLコンソールからクエリを叩いてみる
記法参考
Postgres: Insert mutation > Insert a single object
learn > Chevron Right > intro-graphql > RightGraphQL Mutations > Writing data
知見