使用 Express 的 TypeORM



Express 是一個流行的 JavaScript 框架,用於建立 Web 應用程式。本章我們將學習如何在 TypeORM 中使用 Express 框架。

建立一個簡單的應用程式

TypeORM CLI 提供了一個簡單的選項,可以建立一個與 TypeORM 整合的完整的可執行 Express Web 應用程式(RESTful API 應用程式)。建立應用程式的 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.jsonTypeORM 的配置檔案。程式碼如下:

{ 
   "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 將建立一個預設的 User 模型,如下所示:

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

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

controller 資料夾包含 Express 控制器。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 方法用於使用 使用者 ID 從資料庫中獲取單個使用者。

save 方法用於將使用者資訊儲存到資料庫中。

delete 方法用於使用 使用者 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" 
}];

這裡:

/users URL 對映到使用者控制器。每個動詞 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 https://:3000/users to see results"); 
}).catch(error => console.log(error));

在此處,應用程式配置路由,插入兩個使用者,然後在埠 3000 上啟動 Web 應用程式。我們可以在 https://:3000 訪問應用程式。

要執行應用程式,請按照以下步驟操作:

讓我們使用以下命令安裝必要的包:

npm install

輸出

npm notice created a lockfile as package-lock.json. You should commit this file. 
npm WARN typeorm-express-sample@0.0.1 No repository field. 
npm WARN typeorm-express-sample@0.0.1 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

輸出

> typeorm-express-sample@0.0.1 start /path/to/workspace/typeorm-express-sample 
> ts-node src/index.ts 

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

讓我們使用 curl 命令訪問我們的 Web 應用程式 API,如下所示:

curl https://:3000/users

這裡:

curl 是一個命令列應用程式,用於從命令提示符訪問 Web 應用程式。它支援所有 HTTP 動詞,例如 get、post、delete 等。

輸出

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

要獲取第一條記錄,我們可以使用以下命令:

curl https://:3000/users/1

輸出

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

要刪除使用者記錄,我們可以使用以下命令:

curl -X DELETE https://:3000/users/1

正如我們在本章所看到的,TypeORM 可以輕鬆整合到 Express 應用程式中。

廣告