LoginSignup
0

More than 1 year has passed since last update.

posted at

updated at

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

はじめに

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"
}];

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
What you can do with signing up
0