LoginSignup
0
0

More than 3 years have passed since last update.

【TypeORM × PostgreSQL】RESTful-APIのCRUDを1分で実装する

Last updated at Posted at 2020-11-16

はじめに

30代未経験からエンジニアを目指して勉強中のYNと申します。
タイトルのCRUDの実装をまとめました。TypeORMを使うととても簡単ですね。

セットアップ

cliコマンドを使えば基本的なセットアップは完了です。詳細はこちらを参照ください。

mkdir sample-crud && cd sample-crud
npx typeorm init --database postgres --express --docker
yarn

sample-crudフォルダ内はこんな感じになっているはずです。
スクリーンショット 2020-11-16 15.08.27.png

PostgreSQLコンテナの起動

コンテナを起動します。

docker-compose up -d
docker-compose exec postgres psql -U test

ちゃんと動いていることが確認できます。
スクリーンショット 2020-11-18 16.31.08.png

サーバーを起動

expressサーバーを起動し、データベースを確認します
(このとき、5432portが被るのでホストでPostgreSQLアプリが停止していることを確認してください)

yarn start 

テーブルが作られ、insertクエリが実行されていることを確認できます。
(userは特別な意味を持ち、""を付けないと違う意味のクエリになるので注意しましょう)

スクリーンショット 2020-11-18 16.27.06.png

CRUDクエリの実行

routes.tsに記載のとおりにCRUDが実行できます。あとはControllerの部分を自分好みにカスタマイズしましょう。

routes.ts
export const Routes = [{
    method: "get",
    route: "/users",
    controller: UserController,
    action: "all"
}, {
    method: "get",
    route: "/users/:id",
    controller: UserController,
    action: "one"
}, {
    method: "post",
    route: "/users",
    controller: UserController,
    action: "save"
}, {
    method: "delete",
    route: "/users/:id",
    controller: UserController,
    action: "remove"
}];
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0