📜  具有Express的TypeORM

📅  最后修改于: 2020-10-19 03:45:21             🧑  作者: Mango


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

创建一个简单的应用程序

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

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方法用于从数据库中获取所有用户。

一种方法是使用用户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映射到用户控制器。每个动词发布,获取和删除都映射到不同的方法。

最后, 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可以轻松集成到快速应用程序中。