Skip to content

Main target : {{TypeScript, Express}, {TypeORM, MySQL}} の勉強用

Notifications You must be signed in to change notification settings

RiSEblackbird/_TS_Express_MySQL_with_TypeORM_API

Repository files navigation

_TS_Express_MySQL_with_TypeORM_API

(This repository is my own self-study document )

リポジトリの目的

  • 表題技術の基礎学習
  • 自分用のリファレンス集の作成

下記のチュートリアルを参照させていただきました。

重要なリファレンス

記事

チュートリアルの工程(適宜補完, 変更)

  • package.jsonの初期準備
  • TypeScriptのインストール
  • TypeScriptの設定
    • $ touch tsconfig.json
      • 記事内の設定を適用
  • メインアプリケーションのエンドポイントを作成
    • $ mkdir src
    • $ touch src/app.ts

Linter(ESLint)とFomatter(Prettier)の導入

監視モードでコンパイラを実行

  • concurrently, nodemon, rimraf, npm-run-allインストール

  • package.jsonに監視モード実行のスクリプトを追加

    "scripts": {
      "clean": "rimraf dist/*",
      "tsc": "tsc",
      "build": "npm-run-all clean tsc",
      "start": "concurrently \"tsc -w\" \"nodemon dist/js/app.js\""
    },
  • コンパイルの出力フォルダをsrc/dist/jsに設定

    • taconfig.jsonに出力先DirとルートDirの設定を追記

      "outDir": "dist/js",
      "rootDir": "src",

      さらに下記も追記して、コンパイルに含めるものと除外するものを設定

      "include": ["src/**/*"],
      "exclude": ["node_modules"]

      監視が成功している際のログ

      1:43:28 - Starting compilation in watch mode...
      [0] 
      [1] [nodemon] 2.0.4
      [1] [nodemon] to restart at any time, enter `rs`
      [1] [nodemon] watching path(s): *.*
      [1] [nodemon] watching extensions: js,mjs,json
      [1] [nodemon] starting `node dist/js/app.js`
      [1] [nodemon] clean exit - waiting for changes before restart
      [0] 
      [0] 1:43:30 - Found 0 errors. Watching for file changes.
      [1] [nodemon] restarting due to changes...
      [1] [nodemon] starting `node dist/js/app.js`
      [1] Application is up and running
      [1] [nodemon] clean exit - waiting for changes before restart
      
  • Expressのインストール
    • Express本体のインストール
      • $ yarn add express
    • @types/expressのインストール
      • $ yarn add @types/express --dev
  • src/app.tsにCRUDの処理を記述
  • typeorm, mysql, reflect-metadataのインストール
    • $ yarn add typeorm mysql reflect-metadata --dev
    • reflect-metadataやデコレータの概念は現時点で難解なため後日に回す
  • Userモデルの作成
    • $ mkdir src/entity
    • $ touch src/entity/User.ts
    • 記述を編集

マイグレーション

  • 参考資料

  • 空のマイグレーションファイルを作成

    • $ typeorm migration:generate -n CreateUser
    • $ typeorm migration:generate -n(名前の意) {付けたいファイル名}
    • [ 注意 ] : migration:createだとSQL文の無い空のマイグレーションファイルが生成される
  • 未実行の全てのマイグレーションファイルをDBへ反映させる

    • $ typeorm migration:run

      ## 実行後のDB
      mysql> show tables;
      +-----------------------+
      | Tables_in_typeormtest |
      +-----------------------+
      | migrations            |
      | user                  |
      +-----------------------+
      2 rows in set (0.00 sec)
      
      mysql> describe user;
      +----------+--------------+------+-----+---------+----------------+
      | Field    | Type         | Null | Key | Default | Extra          |
      +----------+--------------+------+-----+---------+----------------+
      | id       | int          | NO   | PRI | NULL    | auto_increment |
      | userName | varchar(255) | NO   |     | NULL    |                |
      | profile  | varchar(255) | NO   |     | NULL    |                |
      +----------+--------------+------+-----+---------+----------------+
      3 rows in set (0.01 sec)

リレーションの作成(1対1, 1対多)

  • 参考資料

  • 最低限のアプリの想定

    • リレーションの実装を演習するために、最低限のCRUDアプリケーションの作成場面を想定する。
    • 調べたりや勉強したキーワードについて、着手歴を可視化、復習タイミングの管理をサポートするサービス。
  • エンティティ構成 for_TS_Express_bigenner_projects-withoutUser(result)

    • 概要
      • keyword : 調べごとの単語や用語
        • word : 単語や用語を登録する
        • memo : 単語/用語の説明や参考URL
      • stamp : keywordについて勉強や調査をしたタイムスタンプ
      • study_log : stampに備考を記入する
        • body : 本文テキスト
    • エンティティ同士の関係性
      • keyword : 1対(0 or 多) : stamp
      • stamp : 1対(0 or 1) : study_log
  • 作成日や更新日を扱えるようにする

    • 各エンティティファイル内で、モジュール : CreateDateColumn,UpdateDateColumn をインポート
  • 1対1

  • 1対多(多対1)

  • DBの最終形

    mysql> show tables;
    +-----------------------+
    | Tables_in_typeormtest |
    +-----------------------+
    | keyword               |
    | migrations            |
    | stamp                 |
    | study_log             |
    +-----------------------+
    4 rows in set (0.02 sec)
    
    mysql> describe keyword;
    +-------------+---------------+------+-----+----------------------+-------------------+
    | Field       | Type          | Null | Key | Default              | Extra             |
    +-------------+---------------+------+-----+----------------------+-------------------+
    | id          | int           | NO   | PRI | NULL                 | auto_increment    |
    | createdDate | datetime(6)   | NO   |     | CURRENT_TIMESTAMP(6) | DEFAULT_GENERATED |
    | updatedDate | datetime(6)   | NO   |     | CURRENT_TIMESTAMP(6) | DEFAULT_GENERATED |
    | memo        | varchar(2000) | NO   |     | NULL                 |                   |
    | word        | varchar(50)   | NO   |     | NULL                 |                   |
    +-------------+---------------+------+-----+----------------------+-------------------+
    5 rows in set (0.03 sec)
    
    mysql> describe stamp;
    +-------------+-------------+------+-----+----------------------+-------------------+
    | Field       | Type        | Null | Key | Default              | Extra             |
    +-------------+-------------+------+-----+----------------------+-------------------+
    | id          | int         | NO   | PRI | NULL                 | auto_increment    |
    | createdDate | datetime(6) | NO   |     | CURRENT_TIMESTAMP(6) | DEFAULT_GENERATED |
    | updatedDate | datetime(6) | NO   |     | CURRENT_TIMESTAMP(6) | DEFAULT_GENERATED |
    | studyLogId  | int         | YES  | UNI | NULL                 |                   |
    | keywordId   | int         | YES  | MUL | NULL                 |                   |
    +-------------+-------------+------+-----+----------------------+-------------------+
    5 rows in set (0.00 sec)
    
    mysql> describe study_log;
    +-------+--------------+------+-----+---------+----------------+
    | Field | Type         | Null | Key | Default | Extra          |
    +-------+--------------+------+-----+---------+----------------+
    | id    | int          | NO   | PRI | NULL    | auto_increment |
    | body  | varchar(500) | NO   |     | NULL    |                |
    +-------+--------------+------+-----+---------+----------------+

CRUD APIの作成

  • コントローラーの作成

    • ライブラリrouting-controllersを使用する

      • リクエストを処理するアクションとしてメソッドを持つコントローラクラスを作成できる。
      • 導入手順はInstallationから
    • $ yarn add routing-controllers --dev

    • $ yarn add class-transformer class-validator --dev

    • コントローラーファイル(src/controllers/**.ts)の作成

  • ルーティングの設定

    • src/app.tsを編集
      • createExpressServer内で各コントローラーを呼び出してポート3000をリッスン
  • サーバーを起動して+ /keywordなどURLを指定すると対応する文字列が出力される

テストツールの導入 : Jest

階層

_TS_Express_MySQL_with_TypeORM
├── dist ── js                       // place of your transpiled JavaScript code
│           ├── controllers          // place where your controllers are stored
│           ├── entity               // place where your entities (database models) are stored
│           ├── migration            // place where your migrations are stored
│           └── app.js               // start point of your application
│
├── src                                  // place of your TypeScript code
│   ├── controllers                      // place where your controllers are stored
│   │   ├── KeywordController.ts  
│   │   ├── StampController.ts
│   │   └── StudyLogController.ts
│   ├── entity                           // place where your entities (database models) are stored
│   │   ├── Keyword.ts  
│   │   ├── Stamp.ts
│   │   └── StudyLog.ts
│   ├── migration                        // place where your migrations are stored
│   └── app.ts                           // start point of your application
│
├── .eslintignore
├── .eslintrc.js
├── .gitignore               // standard gitignore file
├── .prettierignore
├── jest.config.js
├── ormconfig.json           // ORM and database connection configuration
├── package.json             // node module dependencies
├── README.md                // simple readme file
├── tsconfig.json            // TypeScript compiler options
└── yarn.lock

Error

Error: Cannot find module 'express'

[1] Require stack:
[1] - /Users/Taishi/Documents/TypeScript/_TS_Express_MySQL_with_TypeORM/dist/js/app.js
  • [nodemon] app crashed - waiting for file changes before starting...
  • 要因&対処
    • $ yarn add expressの実行抜け -> OK

UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:3306

  • まずMySQLサーバーが起動されていなかった
    • sockファイルやらpidファイルの小さなエラーがあったが対処して起動
    • $ yarn startでのエラーが変わった(おそらく接続はOK)

UnhandledPromiseRejectionWarning: Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client

UnhandledPromiseRejectionWarning: Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'test'@'localhost' (using password: YES)

Releases

No releases published

Packages

No packages published