使用 Express 进行 TypeORM


Express是创建 Web 应用程序的流行 JavaScript 框架之一。让我们在本章中学习如何使用TypeORM和 Express 框架。

创建一个简单的应用程序

TypeORM CLI 提供了一个简单的选项来创建与TypeORM集成的完整工作快速 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 相关的配置。

实体文件夹包含TypeORM模型。CLI 将创建一个默认的用户模型,如下所示:

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

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

控制器文件夹包含快速控制器。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方法用于从数据库中获取所有用户。

一种方法是使用用户 ID从数据库中获取单个用户

save方法用于将用户信息保存到数据库中。

delete方法用于使用用户id从数据库中删除用户

paths.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 http://localhost:3000/users to see results"); 
}).catch(error => console.log(error));

此处,应用程序配置路由,插入两个用户,然后在端口3000启动 Web 应用程序。我们可以通过http://localhost: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 http://localhost:3000/users to see results

让我们使用curl命令访问我们的Web应用程序API,如下所示:

curl http://localhost: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 http://localhost:3000/users/1

输出

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

要删除用户记录,我们可以使用以下命令 -

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

正如我们在本章中看到的,TypeORM可以轻松集成到 Express 应用程序中。