# 在 Express 中使用 TypeORM 的示例

> 英文标题：Example using TypeORM with Express
> 官网原文：https://typeorm.io/docs/guides/example-with-express
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 42 块

---

<!-- EN -->
# Example using TypeORM with Express

<!-- ZH -->
# 在 Express 中使用 TypeORM 的示例

<!-- EN -->
## Initial setup

<!-- ZH -->
## 初始配置

<!-- EN -->
Let's create a simple application called "user" which stores users in the database and allows us to create, update, remove, and get a list of all users, as well as a single user by id within web api.

<!-- ZH -->
我们来创建一个名为 "user" 的简单应用，它把用户存进数据库，并允许我们通过 web api 创建、更新、移除用户，获取所有用户的列表，以及按 id 获取单个用户。

<!-- EN -->
First, create a directory called "user":

<!-- ZH -->
首先，创建一个名为 "user" 的目录：

<!-- EN -->
```shell
mkdir user
```

<!-- ZH -->
```shell
mkdir user
```

<!-- EN -->
Then switch to the directory and create a new project:

<!-- ZH -->
然后切换到该目录并创建一个新项目：

<!-- EN -->
```shell
cd user
npm init
```

<!-- ZH -->
```shell
cd user
npm init
```

<!-- EN -->
Finish the init process by filling in all required application information.

<!-- ZH -->
填入所有必需的应用信息以完成 init 过程。

<!-- EN -->
Now we need to install and setup a TypeScript compiler. Lets install it first:

<!-- ZH -->
现在我们需要安装并配置 TypeScript 编译器。先安装它：

<!-- EN -->
```shell
npm i typescript --save-dev
```

<!-- ZH -->
```shell
npm i typescript --save-dev
```

<!-- EN -->
Then let's create a `tsconfig.json` file which contains the configuration required for the application to compile and run. Create it using your favorite editor and put the following configuration:

<!-- ZH -->
接着我们创建一个 `tsconfig.json` 文件，其中包含应用编译和运行所需的配置。用你喜欢的编辑器创建它，并写入以下配置：

<!-- EN -->
```json
{
    "compilerOptions": {
        "lib": ["es5", "es6", "dom"],
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true
    }
}
```

<!-- ZH -->
```json
{
    "compilerOptions": {
        "lib": ["es5", "es6", "dom"],
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true
    }
}
```

<!-- EN -->
Now let's create a main application endpoint - `app.ts` inside the `src` directory:

<!-- ZH -->
现在我们在 `src` 目录下创建应用的主入口——`app.ts`：

<!-- EN -->
```shell
mkdir src
cd src
touch app.ts
```

<!-- ZH -->
```shell
mkdir src
cd src
touch app.ts
```

<!-- EN -->
Let's add a simple `console.log` inside it:

<!-- ZH -->
在里面加一条简单的 `console.log`：

<!-- EN -->
```typescript
console.log("Application is up and running")
```

<!-- ZH -->
```typescript
console.log("Application is up and running")
```

<!-- EN -->
Now it's time to run our application. To run it, you need to compile your typescript project first:

<!-- ZH -->
现在该运行我们的应用了。要运行它，你需要先编译 typescript 项目：

<!-- EN -->
```shell
tsc
```

<!-- ZH -->
```shell
tsc
```

<!-- EN -->
Once you compile it, you should have a `src/app.js` file generated. You can run it using:

<!-- ZH -->
编译之后，你应该会得到一个生成的 `src/app.js` 文件。你可以用以下命令运行它：

<!-- EN -->
```shell
node src/app.js
```

<!-- ZH -->
```shell
node src/app.js
```

<!-- EN -->
You should see the, "Application is up and running" message in your console right after you run the application.

<!-- ZH -->
运行应用后，你应该立刻在控制台中看到 "Application is up and running" 这条消息。

<!-- EN -->
You must compile your files each time you make a change. Alternatively, you can set up watcher or install [ts-node](https://github.com/TypeStrong/ts-node) to avoid manual compilation each time.

<!-- ZH -->
每次做出改动后你都必须重新编译文件。或者，你可以配置监听器，或安装 [ts-node](https://github.com/TypeStrong/ts-node)，以避免每次都手动编译。

<!-- EN -->
## Adding Express to the application

<!-- ZH -->
## 给应用添加 Express

<!-- EN -->
Let's add Express to our application. First, let's install the packages we need:

<!-- ZH -->
给应用加上 Express。首先安装我们需要的包：

<!-- EN -->
```shell
npm install express
npm install @types/express --save-dev
```

<!-- ZH -->
```shell
npm install express
npm install @types/express --save-dev
```

<!-- EN -->
* `express` is the express engine itself. It allows us to create a web api
* `@types/express` is used to have a type information when using express

<!-- ZH -->
* `express` 是 express 引擎本身。它让我们能够创建 web api
* `@types/express` 用于在使用 express 时获得类型信息

<!-- EN -->
Let's edit the `src/app.ts` file and add express-related logic:

<!-- ZH -->
我们来编辑 `src/app.ts` 文件，加上与 express 相关的逻辑：

<!-- EN -->
```typescript
import * as express from "express"
import { Request, Response } from "express"

// create and setup express app
const app = express()
app.use(express.json())

// register routes

app.get("/users", function (req: Request, res: Response) {
    // here we will have logic to return all users
})

app.get("/users/:id", function (req: Request, res: Response) {
    // here we will have logic to return user by id
})

app.post("/users", function (req: Request, res: Response) {
    // here we will have logic to save a user
})

app.put("/users/:id", function (req: Request, res: Response) {
    // here we will have logic to update a user by a given user id
})

app.delete("/users/:id", function (req: Request, res: Response) {
    // here we will have logic to delete a user by a given user id
})

// start express server
app.listen(3000)
```

<!-- ZH -->
```typescript
import * as express from "express"
import { Request, Response } from "express"

// 创建并配置 express 应用
const app = express()
app.use(express.json())

// 注册路由

app.get("/users", function (req: Request, res: Response) {
    // 这里我们将写返回所有用户的逻辑
})

app.get("/users/:id", function (req: Request, res: Response) {
    // 这里我们将写按 id 返回用户的逻辑
})

app.post("/users", function (req: Request, res: Response) {
    // 这里我们将写保存用户的逻辑
})

app.put("/users/:id", function (req: Request, res: Response) {
    // 这里我们将写按给定用户 id 更新用户的逻辑
})

app.delete("/users/:id", function (req: Request, res: Response) {
    // 这里我们将写按给定用户 id 删除用户的逻辑
})

// 启动 express 服务器
app.listen(3000)
```

<!-- EN -->
Now you can compile and run your project. You should have an express server running now with working routes. However, those routes do not return any content yet.

<!-- ZH -->
现在你可以编译并运行项目了。你应该已经有一个带可用路由的 express 服务器在运行。不过这些路由目前还没有返回任何内容。

<!-- EN -->
## Adding TypeORM to the application

<!-- ZH -->
## 给应用添加 TypeORM

<!-- EN -->
Finally, let's add TypeORM to the application. In this example, we will use `mysql` driver. Setup process for other drivers is similar.

<!-- ZH -->
最后，我们给应用加上 TypeORM。在本示例中，我们使用 `mysql` 驱动。其他驱动的配置过程类似。

<!-- EN -->
Let's install the required packages first:

<!-- ZH -->
先安装所需的包：

<!-- EN -->
```shell
npm install typeorm reflect-metadata mysql
```

<!-- ZH -->
```shell
npm install typeorm reflect-metadata mysql
```

<!-- EN -->
* `typeorm` is the typeorm package itself
* `reflect-metadata` is required to make decorators to work properly. Remember to import it before your TypeORM code.
* `mysql` is the underlying database driver. If you are using a different database system, you must install the appropriate package

<!-- ZH -->
* `typeorm` 是 typeorm 包本身
* `reflect-metadata` 是让装饰器正常工作所必需的。记得在你的 TypeORM 代码之前引入它。
* `mysql` 是底层数据库驱动。如果你使用不同的数据库系统，必须安装相应的包

<!-- EN -->
Let's create `app-data-source.ts` where we set up initial database connection options:

<!-- ZH -->
我们来创建 `app-data-source.ts`，在其中配置初始数据库连接选项：

<!-- EN -->
```ts
import { DataSource } from "typeorm"

export const myDataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
    entities: [__dirname + "/entities/**/*{.js,.ts}"],
    logging: true,
    synchronize: true,
})
```

<!-- ZH -->
```ts
import { DataSource } from "typeorm"

export const myDataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
    entities: [__dirname + "/entities/**/*{.js,.ts}"],
    logging: true,
    synchronize: true,
})
```

<!-- EN -->
Configure each option as you need. Learn more about options [here](https://typeorm.io/docs/data-source/data-source-options).

<!-- ZH -->
按你的需要配置每个选项。在[这里](https://typeorm.io/docs/data-source/data-source-options)进一步了解这些选项。

<!-- EN -->
Let's create a `user.entity.ts` entity under `entities` folder:

<!-- ZH -->
我们在 `entities` 文件夹下创建一个 `user.entity.ts` 实体：

<!-- EN -->
```typescript
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string
}
```

<!-- ZH -->
```typescript
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string
}
```

<!-- EN -->
Let's change `src/app.ts` to establish database connection and start using `myDataSource`:

<!-- ZH -->
我们修改 `src/app.ts`，建立数据库连接并开始使用 `myDataSource`：

<!-- EN -->
```typescript
import "reflect-metadata"

import * as express from "express"
import { Request, Response } from "express"
import { User } from "./entities/User"
import { myDataSource } from "./app-data-source.ts"

// establish database connection
try {
    await myDataSource.initialize()
    console.log("Data Source has been initialized!")
} catch (error) {
    console.error("Error during Data Source initialization:", error)
}

// create and setup express app
const app = express()
app.use(express.json())

// register routes
app.get("/users", async function (req: Request, res: Response) {
    const users = await myDataSource.getRepository(User).find()
    res.json(users)
})

app.get("/users/:id", async function (req: Request, res: Response) {
    const results = await myDataSource.getRepository(User).findOneBy({
        id: req.params.id,
    })
    return res.send(results)
})

app.post("/users", async function (req: Request, res: Response) {
    const user = await myDataSource.getRepository(User).create(req.body)
    const results = await myDataSource.getRepository(User).save(user)
    return res.send(results)
})

app.put("/users/:id", async function (req: Request, res: Response) {
    const user = await myDataSource.getRepository(User).findOneBy({
        id: req.params.id,
    })
    myDataSource.getRepository(User).merge(user, req.body)
    const results = await myDataSource.getRepository(User).save(user)
    return res.send(results)
})

app.delete("/users/:id", async function (req: Request, res: Response) {
    const results = await myDataSource.getRepository(User).delete(req.params.id)
    return res.send(results)
})

// start express server
app.listen(3000)
```

<!-- ZH -->
```typescript
import "reflect-metadata"

import * as express from "express"
import { Request, Response } from "express"
import { User } from "./entities/User"
import { myDataSource } from "./app-data-source.ts"

// 建立数据库连接
try {
    await myDataSource.initialize()
    console.log("Data Source has been initialized!")
} catch (error) {
    console.error("Error during Data Source initialization:", error)
}

// 创建并配置 express 应用
const app = express()
app.use(express.json())

// 注册路由
app.get("/users", async function (req: Request, res: Response) {
    const users = await myDataSource.getRepository(User).find()
    res.json(users)
})

app.get("/users/:id", async function (req: Request, res: Response) {
    const results = await myDataSource.getRepository(User).findOneBy({
        id: req.params.id,
    })
    return res.send(results)
})

app.post("/users", async function (req: Request, res: Response) {
    const user = await myDataSource.getRepository(User).create(req.body)
    const results = await myDataSource.getRepository(User).save(user)
    return res.send(results)
})

app.put("/users/:id", async function (req: Request, res: Response) {
    const user = await myDataSource.getRepository(User).findOneBy({
        id: req.params.id,
    })
    myDataSource.getRepository(User).merge(user, req.body)
    const results = await myDataSource.getRepository(User).save(user)
    return res.send(results)
})

app.delete("/users/:id", async function (req: Request, res: Response) {
    const results = await myDataSource.getRepository(User).delete(req.params.id)
    return res.send(results)
})

// 启动 express 服务器
app.listen(3000)
```

<!-- EN -->
Now you should have a basic express application connected to MySQL database up and running.

<!-- ZH -->
现在你应该已经有一个连接到 MySQL 数据库的基础 express 应用在运行了。
