TypeORM với Express

Express là một trong những khung JavaScript phổ biến để tạo ứng dụng web. Hãy để chúng tôi học cách sử dụngTypeORM cùng với khung thể hiện trong chương này.

Tạo một ứng dụng đơn giản

TypeORM CLI cung cấp một tùy chọn dễ dàng để tạo một ứng dụng web nhanh hoạt động hoàn chỉnh (ứng dụng API Restful) được tích hợp với TypeORM. Lệnh CLI để tạo ứng dụng như sau:

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

Lệnh trên sẽ tạo một ứng dụng web mới trong thư mục typeorm-express-sample. Cấu trúc của ứng dụng như sau:

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

Đây,

Như chúng ta biết, ormconfig.jsonTypeORMtập tin cấu hình. Mã như sau,

{ 
   "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" 
   } 
}

Tại đây, hãy thay đổi cài đặt cơ sở dữ liệu để phù hợp với cài đặt cơ sở dữ liệu cục bộ của bạn.

package.json tệp là cấu hình chính của ứng dụng.

tsconfig.json tệp chứa cấu hình liên quan đến TypeScript.

entity thư mục chứa TypeORMcác mô hình. Mô hình người dùng mặc định sẽ được tạo bởi CLI và nó như sau:

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

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

controllerthư mục chứa các bộ điều khiển nhanh. CLI tạo bộ điều khiển API người dùng mặc định với thêm / danh sách / xóa chi tiết người dùng. Mã như sau:

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

Đây,

all được sử dụng để tìm nạp tất cả người dùng từ cơ sở dữ liệu.

one phương thức được sử dụng để tìm nạp một người dùng từ cơ sở dữ liệu bằng cách sử dụng user id

save được sử dụng để lưu thông tin người dùng vào cơ sở dữ liệu.

delete phương pháp được sử dụng để xóa người dùng khỏi cơ sở dữ liệu bằng cách sử dụng user id

routes.ts tệp ánh xạ các phương thức của bộ điều khiển người dùng tới URL thích hợp và mã như sau:

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

Đây,

/ users url được ánh xạ tới bộ điều khiển người dùng. Mỗi bài đăng động từ, nhận và xóa được ánh xạ đến các phương thức khác nhau.

Cuối cùng, index.tslà điểm vào ứng dụng web chính của chúng tôi. Mã nguồn như sau:

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

Tại đây, ứng dụng định cấu hình các tuyến đường, chèn hai người dùng và sau đó khởi động ứng dụng web ở cổng 3000 . Chúng ta có thể truy cập ứng dụng tạihttp://localhost:3000

Để chạy ứng dụng, hãy làm theo các bước sau:

Hãy để chúng tôi cài đặt các gói cần thiết bằng lệnh dưới đây -

npm install

Đầu ra

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

Chạy lệnh dưới đây để khởi động ứng dụng.

npm start

Đầu ra

> [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

Hãy để chúng tôi truy cập API ứng dụng web của chúng tôi bằng lệnh curl như bên dưới:

curl http://localhost:3000/users

Đây,

curl là một ứng dụng dòng lệnh để truy cập ứng dụng web từ dấu nhắc lệnh. Nó hỗ trợ tất cả các động từ HTTP như get, post, delete, v.v.,

Đầu ra

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

Để tìm nạp bản ghi đầu tiên, chúng ta có thể sử dụng lệnh dưới đây:

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

Đầu ra

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

Để xóa bản ghi người dùng, chúng ta có thể sử dụng lệnh dưới đây:

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

Như chúng ta đã thấy trong chương này, TypeORM có thể dễ dàng tích hợp vào ứng dụng nhanh.