Expressを使用したTypeORM

Expressは、Webアプリケーションを作成するための人気のあるJavaScriptフレームワークの1つです。使い方を学びましょうTypeORM この章のエクスプレスフレームワークとともに。

簡単なアプリケーションの作成

TypeORM CLIは、と統合された完全に機能するExpress Webアプリケーション(Restful APIアプリケーション)を作成するための簡単なオプションを提供します。 TypeORM。アプリケーションを作成するためのCLIコマンドは次のとおりです。

cd /path/to/workspace typeorm init --express --name typeorm-express-sample --database mysql

上記のコマンドは、typeorm-express-sampleフォルダーの下に新しいWebアプリケーションを作成します。アプリケーションの構造は次のとおりです-

│ .gitignore 
│ ormconfig.json 
│ package.json 
│ README.md 
│ tsconfig.json 
│ └───src 
      │ index.ts 
      │ routes.ts 
      │ 
      ├───controller 
      │      UserController.ts 
      │ 
      ├───entity 
      │      User.ts 
      │ 
      └───migration

ここに、

みなさんご存じのとおり、 ormconfig.json それは TypeORM構成ファイル。コードは次のとおりです。

{ 
   "type": "mysql", 
   "host": "localhost", 
   "port": 3306, 
   "username": "test", 
   "password": "test", 
   "database": "test", 
   "synchronize": true, 
   "logging": false, 
   "entities": [
      "src/entity/**/*.ts" 
   ], 
   "migrations": [ "src/migration/**/*.ts" 
   ], 
   "subscribers": [ "src/subscriber/**/*.ts" 
   ], 
   "cli": { 
      "entitiesDir": "src/entity", "migrationsDir": "src/migration", "subscribersDir": "src/subscriber" 
   } 
}

ここで、ローカルデータベース設定と一致するようにデータベース設定を変更します。

package.json ファイルは、アプリケーションの主な構成です。

tsconfig.json ファイルには、TypeScriptに関連する構成が含まれています。

entity フォルダには、 TypeORMモデル。デフォルトのユーザーモデルはCLIによって作成され、次のようになります。

import {Entity, PrimaryGeneratedColumn, Column} from "typeorm"; 

@Entity() 
export class User { 
   
   @PrimaryGeneratedColumn() 
   id: number; 
   
   @Column() 
   firstName: string; 
   
   @Column() 
   lastName: string; 
   
   @Column() 
   age: number; 
}

controllerフォルダにはエクスプレスコントローラが含まれています。CLIは、ユーザーの詳細を追加/一覧表示/削除して、デフォルトのユーザーAPIコントローラーを作成します。コードは次のとおりです-

import {getRepository} from "typeorm"; import {NextFunction, Request, Response} from "express"; import {User} from "../entity/User"; 

export class UserController {

   private userRepository = getRepository(User); 
   
   async all(request: Request, response: Response, next: NextFunction) { 
      return this.userRepository.find(); 
   } 
   
   async one(request: Request, response: Response, next: NextFunction) { 
      return this.userRepository.findOne(request.params.id); 
   } 
   
   async save(request: Request, response: Response, next: NextFunction) { 
      return this.userRepository.save(request.body); 
   } 
   
   async remove(request: Request, response: Response, next: NextFunction) { 
      let userToRemove = await this.userRepository.findOne(request.params.id); 
      await this.userRepository.remove(userToRemove); 
   } 
}

ここに、

all メソッドは、データベースからすべてのユーザーをフェッチするために使用されます。

one メソッドは、を使用してデータベースから単一のユーザーをフェッチするために使用されます user id

save メソッドは、ユーザー情報をデータベースに保存するために使用されます。

delete メソッドは、を使用してデータベースからユーザーを削除するために使用されます user id

routes.ts ファイルはユーザーコントローラーメソッドを適切なURLにマップし、コードは次のとおりです。

import {UserController} from "./controller/UserController"; 

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

ここに、

/ usersurlはユーザーコントローラーにマップされます。各動詞post、get、およびdeleteは、異なるメソッドにマップされます。

最終的に、 index.tsは、メインのWebアプリケーションのエントリポイントです。ソースコードは以下の通りです−

import "reflect-metadata"; 
import {createConnection} from "typeorm"; 
import * as express from "express"; import * as bodyParser from "body-parser"; 
import {Request, Response} from "express"; 
import {Routes} from "./routes"; import {User} from "./entity/User"; 

createConnection().then(async connection => { 

   // create express app const app = express(); app.use(bodyParser.json()); 

   // register express routes from defined application routes Routes.forEach(route => { 
      (app as any)[route.method](route.route, (req:   Request, res: Response, next: Function) => { 
         const result = (new (route.controller as any))[route.action](req, res, next); 
         if (result instanceof Promise) { 
            result.then(result => result !== null && result !== undefined ? res.send(result) : undefined); 
         } else if (result !== null && result !== undefined) { 
            .json(result); 
         } 
      }); 
   }); 
      
   // setup express app here 
   // ... 
      
   // start express server app.listen(3000); 
      
   // insert new users for test await connection.manager.save(connection.manager.create(User, { 
      firstName: "Timber",
      lastName: "Saw", 
      age: 27 
   }));
   await connection.manager.save(connection.manager.create(User, { 
      firstName: "Phantom", 
      lastName: "Assassin", 
      age: 24 
   })); 
      
   console.log("Express server has started on port 3000. Open http://localhost:3000/users to see results"); 
}).catch(error => console.log(error));

ここで、アプリケーションはルートを構成し、2人のユーザーを挿入してから、ポート3000でWebアプリケーションを起動します。私たちはでアプリケーションにアクセスすることができますhttp://localhost:3000

アプリケーションを実行するには、以下の手順に従います-

以下のコマンドを使用して、必要なパッケージをインストールしましょう-

npm install

出力

npm notice created a lockfile as package-lock.json. You should commit this file. 
npm WARN [email protected] No repository field. 
npm WARN [email protected] No license field. 

added 176 packages from 472 contributors and audited 351 packages in 11.965s 

3 packages are looking for funding  run `npm fund` for details 

found 0 vulnerabilities

以下のコマンドを実行して、アプリケーションを起動します。

npm start

出力

> [email protected] start /path/to/workspace/typeorm-express-sample 
> ts-node src/index.ts 

Express server has started on port 3000. Open http://localhost:3000/users to see results

以下のようにcurlコマンドを使用してWebアプリケーションAPIにアクセスしましょう-

curl http://localhost:3000/users

ここに、

curlは、コマンドプロンプトからWebアプリケーションにアクセスするためのコマンドラインアプリケーションです。get、post、deleteなどのすべてのHTTP動詞をサポートします。

出力

[{"id":1,"firstName":"Timber","lastName":"Saw","age":27},{"id":2,"firstName":"Phantom","lastName":"Assassin","age":24}]

最初のレコードをフェッチするには、以下のコマンドを使用できます-

curl http://localhost:3000/users/1

出力

{"id":1,"firstName":"Timber","lastName":"Saw","age":27}

ユーザーレコードを削除するには、以下のコマンドを使用できます-

curl -X DELETE http://localhost:3000/users/1

この章で見たように、 TypeORM エクスプレスアプリケーションに簡単に統合できます。