---
title: '第 3 章：项目搭建'
---

来源：https://mikro-orm.io/docs/guide/project-setup

到目前为止你都只是在拿实体做试验，现在开始构建真正的东西。如前所述，你会使用 Fastify 作为 Web 服务器，用 Vitest 测试它。我们来把它搭起来，创建第一个端点并测试它。

<a id="fastify"></a>
## Fastify

在 `src` 目录下新建 `app.ts` 文件，并从中导出一个 `bootstrap` 函数，在其中创建 fastify 应用实例。还记得你是如何 fork [`EntityManager`](https://mikro-orm.io/api/core/class/EntityManager) 来绕过全局上下文校验的吗？对于 Web 服务器，你可以借助中间件（在 fastify 中则是钩子）自动获得每个请求独立的上下文。MikroORM 提供了一个名为 `RequestContext` 的便捷辅助工具，可以用来为每个请求创建 fork。[`EntityManager`](https://mikro-orm.io/api/core/class/EntityManager) 知道这个类的存在，并会自动尝试从中获取正确的上下文。

:::info `RequestContext` 辅助工具是如何工作的？

在内部，所有会用到标识映射的 [`EntityManager`](https://mikro-orm.io/api/core/class/EntityManager) 方法（例如 [`em.find()`](https://mikro-orm.io/api/core/class/EntityManager#find) 或 [`em.getReference()`](https://mikro-orm.io/api/core/class/EntityManager#getReference)）都会先调用 `em.getContext()` 来访问上下文化的 fork。该方法会先检查当前代码是否运行在 `RequestContext` 处理器内部，并优先使用其中的 [`EntityManager`](https://mikro-orm.io/api/core/class/EntityManager) fork。

```ts
// 我们在全局 EM 实例上调用 em.find()
const res = await orm.em.find(Book, {});

// 但在底层它会被解析为
const res = await orm.em.getContext().find(Book, {});

// 而这又会被解析为
const res = await RequestContext.getEntityManager().find(Book, {});
```

`RequestContext.getEntityManager()` 方法随后会检查 `AsyncLocalStorage` 静态实例——`RequestContext.create()` 方法正是用它来创建新的 EM fork 的。

Node.js 核心中的 [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage) 类就是这里的魔术师。它让我们能够在整个异步调用链中追踪上下文。它也让我们可以把 [`EntityManager`](https://mikro-orm.io/api/core/class/EntityManager) fork 的创建（通常在中间件中完成，如上一节所示）与通过全局 [`EntityManager`](https://mikro-orm.io/api/core/class/EntityManager) 实例对它的使用解耦开来。

:::

```ts title='app.ts'
import { MikroORM, RequestContext } from '@mikro-orm/core';
import { fastify } from 'fastify';
import config from './mikro-orm.config.js';

export async function bootstrap(port = 3001) {
  const orm = await MikroORM.init(config);
  const app = fastify();

  // 注册请求上下文钩子
  app.addHook('onRequest', (request, reply, done) => {
    RequestContext.create(orm.em, done);
  });

  // 关闭应用时断开连接
  app.addHook('onClose', async () => {
    await orm.close();
  });

  // 在这里注册路由
  // ...

  const url = await app.listen({ port });

  return { app, url };
}
```

然后在 `server.ts` 文件中使用这个函数——你可以把目前为止的所有代码清空，替换成下面这样：

```ts title='server.ts'
import { bootstrap }  from './app.js';

try {
  const { url } = await bootstrap();
  console.log(`server started at ${url}`);
} catch (e) {
  console.error(e);
}
```

现在再次运行 `npm start`，你应该会看到类似这样的输出：

```
[info] MikroORM version: 7.0.0
[discovery] ORM entity discovery started
[discovery] - processing entity User
[discovery] - processing entity Article
[discovery] - processing entity Tag
[discovery] - processing entity BaseEntity
[discovery] - entity discovery finished, found 5 entities, took 5 ms
[info] MikroORM successfully connected to database sqlite.db
server started at http://127.0.0.1:3001
```

服务器跑起来了，很好！要停止它，按 `CTRL + C`。

<a id="user-profile-endpoint"></a>
### 用户资料端点

我们来添加第一个端点——`GET /article`，它会列出所有已有文章。这是一个公开端点，可以接受 `limit` 与 `offset` 查询参数，并返回请求的条目以及所有可用文章的总数。

你可以用 `em.count()` 获取实体数量，但既然你想把总数和分页后的实体列表一起返回，有更好的办法——`em.findAndCount()`。这个方法正是为此而生，它会返回分页列表以及条目总数。

```ts title='app.ts'
app.get('/article', async request => {
  const { limit, offset } = request.query as { limit?: number; offset?: number };
  const [items, total] = await orm.em.findAndCount(ArticleSchema, {}, {
    limit, offset,
  });

  return { items, total };
});
```

<a id="basic-dependency-injection-container"></a>
## 基础依赖注入容器

在测试第一个端点之前，我们先稍微重构一下，让整体结构更面向未来。新增一个 `src/db.ts` 文件，它将充当一个简单的依赖注入（DI）容器。它会导出 `initORM()` 函数：该函数首先初始化 ORM 并把它缓存到内存中，这样后续调用就会返回同一个实例。得益于顶层 await，你本可以直接初始化 ORM 并立刻导出它，但很快你就会出于测试目的想在初始化之前调整某些选项，而拥有这样一个函数会有助于做到这一点。

> 注意，你是从 `@mikro-orm/sqlite` 包中导入 `EntityManager`、`EntityRepository`、`MikroORM`、`Options` 的——这些导出的类型都绑定到 `SqliteDriver`。

```ts title='db.ts'
import { EntityManager, EntityRepository, MikroORM, Options } from '@mikro-orm/sqlite';
import { UserSchema, type User } from './modules/user/user.entity.js';
import { ArticleSchema, type IArticle } from './modules/article/article.entity.js';
import { TagSchema, type ITag } from './modules/article/tag.entity.js';
import config from './mikro-orm.config.js';

export interface Services {
  orm: MikroORM;
  em: EntityManager;
  article: EntityRepository<IArticle>;
  user: EntityRepository<User>;
  tag: EntityRepository<ITag>;
}

let cache: Services;

export function initORM(options?: Partial<Options>): Services {
  if (cache) {
    return cache;
  }

  const orm = new MikroORM({
    ...config,
    ...options,
  });

  // 返回前先存入缓存
  return cache = {
    orm,
    em: orm.em,
    article: orm.em.getRepository(ArticleSchema),
    user: orm.em.getRepository(UserSchema),
    tag: orm.em.getRepository(TagSchema),
  };
}
```

然后在 `app.ts` 文件中使用它，而不是直接初始化 ORM：

```ts title='app.ts'
import { RequestContext } from '@mikro-orm/core';
import { fastify } from 'fastify';
import { initORM } from './db.js';

export async function bootstrap(port = 3001) {
  const db = initORM();
  const app = fastify();

  // 注册请求上下文钩子
  app.addHook('onRequest', (request, reply, done) => {
    RequestContext.create(db.em, done);
  });

  // 关闭应用时断开连接
  app.addHook('onClose', async () => {
    await db.orm.close();
  });

  // 在这里注册路由
  app.get('/article', async request => {
    const { limit, offset } = request.query as { limit?: number; offset?: number };
    const [items, total] = await db.article.findAndCount({}, {
      limit, offset,
    });

    return { items, total };
  });

  const url = await app.listen({ port });

  return { app, url };
}
````

:::info 从驱动包导入 `EntityManager` 与 `EntityRepository`

虽然 [`EntityManager`](https://mikro-orm.io/api/core/class/EntityManager) 与 [`EntityRepository`](https://mikro-orm.io/api/core/class/EntityRepository) 类由 `@mikro-orm/core` 包提供，但那些只是基础实现——与驱动无关。举个例子：作为 SQL 概念的 `QueryBuilder` 在 `@mikro-orm/core` 包中无处安放，取而代之，SQL 驱动包提供了 [`EntityManager`](https://mikro-orm.io/api/core/class/EntityManager) 的一个扩展类 `SqlEntityManager`（它定义在 `@mikro-orm/sql` 包中，并在每个依赖它的 SQL 驱动包中重新导出）。这个 `SqlEntityManager` 类提供了额外的 SQL 相关方法，例如 `em.createQueryBuilder()`。

为了方便，`SqlEntityManager` 类还会以 [`EntityManager`](https://mikro-orm.io/api/core/class/EntityManager) 别名重新导出。这意味着你可以写 `import { EntityManager } from '@mikro-orm/sqlite'` 来访问它。

在底层，MikroORM 总是会使用这个驱动专属的 [`EntityManager`](https://mikro-orm.io/api/core/class/EntityManager) 实现（你可以通过 `console.log(orm.em)` 验证，它会是 `SqlEntityManager` 的实例），但要让 TypeScript 理解这一点，你需要从驱动包导入它。[`EntityRepository`](https://mikro-orm.io/api/core/class/EntityRepository) 与 `SqlEntityRepository` 类同理。

```ts
import { EntityManager, EntityRepository } from '@mikro-orm/sqlite'; // 或任意其他驱动包
```

你也可以使用从驱动包导出的 `MikroORM`、`defineConfig` 与 `Options`，其工作方式类似——无需使用泛型即可获得驱动类型。

:::

<a id="what-is-entityrepository"></a>
### 什么是 `EntityRepository`

实体仓库是位于 [`EntityManager`](https://mikro-orm.io/api/core/class/EntityManager) 之上的薄层。它们充当扩展点，因此你可以添加自定义方法，甚至改写已有方法。默认的 [`EntityRepository`](https://mikro-orm.io/api/core/class/EntityRepository) 实现只是把调用转发给底层的 [`EntityManager`](https://mikro-orm.io/api/core/class/EntityManager) 实例。

[`EntityRepository`](https://mikro-orm.io/api/core/class/EntityRepository) 类携带了实体类型，因此你不必在每次 `find` 或 `findOne` 调用时都传入它。

注意，并不存在所谓「flush 一个仓库」——它只是 [`em.flush()`](https://mikro-orm.io/api/core/class/EntityManager#flush) 的快捷方式。换句话说，我们总是 flush 整个工作单元，而不仅仅是该仓库所代表的单个实体。

<a id="testing-the-endpoint"></a>
## 测试端点

第一个端点已经就绪，我们来测试它。你已经安装好 `vitest`，可以通过 `npm test` 使用，现在添加一个测试用例。把它放进 `test` 文件夹，并用 `.test.ts` 扩展名命名，这样 `vitest` 就知道它是测试文件。

那么该如何测试这个端点呢？Fastify 提供了通过 `app.inject()` 测试端点的便捷方式，你只需要在测试用例中创建 fastify 应用实例（你已经为此准备好了 `bootstrap` 方法）。但那样会针对你的生产数据库做测试——你并不想这样！

在写第一个测试之前，我们再创建一个工具文件，同样放进 `test` 文件夹，但不带 `.test.ts` 后缀——就叫 `utils.ts`。你会在其中定义一个名为 `initTestApp` 的函数，它会用覆盖后的测试选项初始化 ORM、创建 schema 并引导启动 fastify 应用，一气呵成。它会接收 `port` 端口号作为参数，同样是为了在测试时便于并行运行——每个测试用例都会拥有自己的内存数据库，以及运行在自己端口上的 fastify 应用。

```ts title='utils.ts'
import { bootstrap } from '../src/app.js';
import { initORM } from '../src/db.js';
import config from '../src/mikro-orm.config.js';

export async function initTestApp(port: number) {
  // 这会创建所有 ORM 服务并把它们缓存起来
  const { orm } = initORM({
    // 首先，引入主配置
    ...config,
    // 不需要调试信息，那只会污染日志
    debug: false,
    // 使用内存数据库，这样测试就能轻松并行化
    dbName: ':memory:',
  });

  // 创建 schema，数据库才能被使用
  await orm.schema.create();

  const { app } = await bootstrap(port);

  return app;
}
```

现在终于轮到测试用例了。目前数据库里没有数据，因为你用的是空的内存数据库，每次测试运行都是全新的，所以文章列表端点只会返回一个空数组——你马上就会处理这一点。

> 注意你用 `beforeAll` 钩子初始化应用，用 `afterAll` 拆除它——`app.close()` 会触发 `onClose` 钩子，后者会调用 `orm.close()`。没有这一步，进程会挂住。

```ts title='article.test.ts'
import { afterAll, beforeAll, expect, test } from 'vitest';
import { FastifyInstance } from 'fastify';
import { initTestApp } from './utils.js';

let app: FastifyInstance;

beforeAll(async () => {
  // 使用不同端口以支持并行测试
  app = await initTestApp(30001);
});

afterAll(async () => {
  // 我们只关闭 fastify 应用——它会通过 onClose 钩子自动关闭数据库连接
  await app.close();
});

test('list all articles', async () => {
  // 通过 `app.inject()` 模拟 http 请求
  const res = await app.inject({
    method: 'get',
    url: '/article',
  });

  // 断言这是成功的响应
  expect(res.statusCode).toBe(200);

  // 且结构符合预期
  expect(res.json()).toMatchObject({
    items: [],
    total: 0,
  });
});
```

现在运行 `npm test`，应该一切正常：

```
 ✓ test/article.test.ts (1)

Test Files  1 passed (1)
    Tests  1 passed (1)
  Start at  15:56:41
  Duration  876ms (transform 264ms, setup 0ms, collect 300ms, tests 147ms)


 PASS  Waiting for file changes...
     press h to show help, press q to quit
```

<a id="note-about-unit-tests"></a>
### 关于单元测试的说明

在某些不需要数据库连接的单元测试中，你可能会想跳过 `MikroORM.init()` 阶段，但 `init` 方法**做的不止**建立连接这一件事。该方法最重要的部分是元数据发现——ORM 会在这一阶段检查所有实体定义，并为各种元数据选项设置默认值（主要是命名策略与双向关联）。

发现阶段是 **[传播](./56-propagation.md) 生效的必要条件**。

```ts
const orm = new MikroORM({
  // ...
});
```

<a id="seeding-the-database"></a>
## 为数据库写入种子数据

为测试数据库写入种子数据有很多种方式。最直白的做法是直接在测试里做，例如在 `beforeAll` 钩子中、初始化 ORM 之后立刻执行。

另一种选择是使用 Seeder——一个 ORM 包（通过 `@mikro-orm/seeder` 提供），它提供了一些工具来用（不一定是）假数据填充数据库。

> 你会用 Seeder 为测试数据库填充假数据，但用 seeder 为生产数据库创建初始数据同样是合理的做法——你可以用这种方式创建默认的文章标签集合，或者初始管理员用户。你可以搭建 seeder 的层级结构，也可以逐个调用它们。

我们来安装 seeder 包，并用 CLI 生成一个测试 seeder：

```bash npm2yarn
npm install @mikro-orm/seeder
```

下一步是在 ORM 配置中注册 `SeedManager` 扩展，这会让它可通过 `orm.seeder` 属性访问：

```ts
import { defineConfig } from '@mikro-orm/sqlite';
import { SeedManager } from '@mikro-orm/seeder';

export default defineConfig({
  // ...
  extensions: [SeedManager],
});
```

> 其他可用的扩展还有 `SchemaGenerator`、`Migrator` 与 `EntityGenerator`。`SchemaGenerator`（以及 `MongoSchemaGenerator`）会自动注册，因为它不需要安装任何第三方依赖。

现在试着创建一个名为 `test` 的新 seeder：

```bash
npx mikro-orm seeder:create test
```

这会创建 `src/seeders` 目录，并在其中生成 `TestSeeder.ts` 文件，里面是新 seeder 的骨架：

```ts title='TestSeeder.ts'
import type { EntityManager } from '@mikro-orm/core';
import { Seeder } from '@mikro-orm/seeder';

export class TestSeeder extends Seeder {

  async run(em: EntityManager): Promise<void> {}

}
```

你可以使用前面介绍过的 [`em.create()`](https://mikro-orm.io/api/core/class/EntityManager#create) 函数。它在返回创建出的实体之前实际上会调用 `em.persist(entity)`，所以你甚至不需要对实体本身做任何处理，单独调用 [`em.create()`](https://mikro-orm.io/api/core/class/EntityManager#create) 就足够了。是时候测试它了！

```ts title='TestSeeder.ts'
export class TestSeeder extends Seeder {

  async run(em: EntityManager): Promise<void> {
    em.create(UserSchema, {
      fullName: 'Foo Bar',
      email: 'foo@bar.com',
      password: 'password123',
      articles: [
        {
          title: 'title 1/3',
          description: 'desc 1/3',
          text: 'text text text 1/3',
          tags: [{ id: 1, name: 'foo1' }, { id: 2, name: 'foo2' }],
        },
        {
          title: 'title 2/3',
          description: 'desc 2/3',
          text: 'text text text 2/3',
          tags: [{ id: 2, name: 'foo2' }],
        },
        {
          title: 'title 3/3',
          description: 'desc 3/3',
          text: 'text text text 3/3',
          tags: [{ id: 2, name: 'foo2' }, { id: 3, name: 'foo3' }],
        },
      ],
    });
  }

}
```

然后你需要运行 `TestSeeder`，我们就在 `initTestApp` 辅助函数里做这件事，放在调用 `orm.schema.create()` 之后：

```ts title='utils.ts'
await orm.schema.create();
await orm.seeder.seed(TestSeeder);
```

并调整测试断言，因为现在列表里会有 3 篇文章：

```ts title='article.test.ts'
expect(res.json()).toMatchObject({
  items: [
    { author: 1, slug: 'title-13', title: 'title 1/3' },
    { author: 1, slug: 'title-23', title: 'title 2/3' },
    { author: 1, slug: 'title-33', title: 'title 3/3' },
  ],
  total: 3,
});
```

现在运行 `npm test`，验证一切符合预期。

目前这样就足够了，不过别担心，稍后你还会回到这个话题。

<a id="schemagenerator"></a>
## SchemaGenerator

在指南前面，当你需要为测试创建数据库时，你用 `SchemaGenerator` 重建了数据库。我们来多聊一点这个类。

[`SchemaGenerator`](./36-schema-generator.md) 负责根据你的实体元数据生成 SQL 查询。换句话说，它把实体定义翻译成数据定义语言（DDL）。此外，它还能理解你当前的数据库 schema，并把它与元数据做比对，从而得出让 schema 保持同步所需的查询。

它可以以编程方式使用：

```ts
// 获取查询语句
const diff = await orm.schema.getUpdateSchemaSQL();
console.log(diff);

// 或者直接执行这些查询
await orm.schema.update();
```

> 借助 `orm.schema.update()`，你可以轻松实现与 TypeORM 的 `synchronize: true` 相同的行为——只需把它放在 ORM 初始化之后（或者放在应用的某段引导代码中）。请记住，这种做法可能具有破坏性，因此不被推荐——在执行之前，你应当始终先确认 `SchemaGenerator` 生成了哪些查询！

或者通过 CLI：

> 要真正执行查询，把 `--dump` 换成 `--run`。

```bash
npx mikro-orm schema:create --dump  # 输出创建 schema 的 SQL
npx mikro-orm schema:update --dump  # 输出更新 schema 的 SQL
npx mikro-orm schema:drop --dump    # 输出删除 schema 的 SQL
```

你的生产数据库（项目根目录下 `sqlite.db` 文件中的那个）很可能已经不同步了，因为你在测试中主要使用的是内存数据库。我们试着通过 CLI 把它同步一下。首先，带上 `--dump`（或 `-d`）标志运行，看看它会生成哪些查询，然后再用 `--run`（或 `-r`）执行它们：

```bash
# 先看看会生成什么
npx mikro-orm schema:update --dump

# 确认没问题后，同步 schema
npx mikro-orm schema:update --run
```

> 如果这条命令不起作用并产生了某些无效查询，你随时可以先调用 `schema:drop --run`，然后从头重建 schema。

在搭建应用原型时，或者特别是在测试场景中（你可能希望拥有许多个带最新 schema 的数据库，而不管生产 schema 是什么样），使用 `SchemaGenerator` 会很方便。但要小心，在真正的生产数据库上使用它可能非常危险。幸运的是，这有解决方案——迁移。

<a id="migrations"></a>
## 迁移

> 要使用迁移，你首先需要为 SQL 驱动安装 `@mikro-orm/migrations` 包（MongoDB 则用 `@mikro-orm/migrations-mongodb`），并在 ORM 配置中注册 `Migrator` 扩展。

MikroORM 内置了对迁移的支持。它允许你根据当前的 schema 差异生成迁移，并管理它们的执行。默认情况下，每个迁移都会在一个事务内执行，并且所有迁移会被包裹在一个主事务中，因此只要其中一个失败，全部都会回滚。

我们来安装 migrations 包，并尝试创建你的第一个迁移：

```bash npm2yarn
npm install @mikro-orm/migrations
```

然后在 ORM 配置中注册 `Migrator` 扩展：

```ts
import { defineConfig } from '@mikro-orm/sqlite';
import { SeedManager } from '@mikro-orm/seeder';
import { Migrator } from '@mikro-orm/migrations';

export default defineConfig({
  // ...
  extensions: [SeedManager, Migrator],
});
```

最后试着创建你的第一个迁移：

```bash
npx mikro-orm migration:create
```

如果你一直紧跟本指南，应该会看到这条消息：

```
No changes required, schema is up-to-date
```

这是因为你刚才已经通过 `npx mikro-orm schema:update --run` 同步过 schema 了。这里你有两个选择：先删除 schema，或者破坏性更小的做法——创建初始迁移。

<a id="initial-migration"></a>
### 初始迁移

如果你想开始使用迁移，而 schema 已经生成好了，`--initial` 标志能帮你保留现有 schema，同时仅基于实体元数据生成第一个迁移。它只能在 schema 为空或完全是最新的情况下使用。如果你的 schema 已经存在，生成的迁移会被自动标记为已执行——如果不存在，你就需要像执行其他任何迁移一样，通过 `npx mikro-orm migration:up` 手动执行它。

> 只有在之前没有生成或执行过任何迁移时，才能创建初始迁移。如果你是从零开始、还没有 schema，就不需要使用 `--inital` 标志，常规迁移同样能完成任务。

```sh
npx mikro-orm migration:create --initial
```

这会在 `src/migrations` 目录中创建初始迁移，其中包含来自 `schema:create` 命令的查询。由于你的 schema 已经同步，该迁移会被自动标记为已执行。

<a id="migration-class"></a>
### 迁移类

我们来看一下生成的迁移。你会看到其中有一个类，它继承了 `@mikro-orm/migrations` 包中的 `Migration` 抽象类：

```ts title='Migration20220913202829.ts'
import { Migration } from '@mikro-orm/migrations';

export class Migration20220913202829 extends Migration {

  async up(): Promise<void> {
    this.addSql('create table `tag` (`id` integer not null primary key autoincrement, `created_at` datetime not null, `updated_at` datetime not null, `name` text not null);');
    // ...
  }

}
```

为了支持撤销这些变更，你可以实现 `down` 方法——它默认会抛出错误。

:::info 回滚迁移与 SQLite

MikroORM 会自动生成回滚迁移（出于安全考虑，初始迁移除外），只有一个例外——SQLite 驱动，因为它的能力有限。如果你使用任何其他驱动，都会生成回滚迁移（除非它是初始迁移）。

:::

> 你也可以在 `up()`／`down()` 方法中通过 `this.execute('...')` 执行查询，它会在与迁移其余部分相同的事务中运行。`this.addSql('...)` 方法还接受原生查询构建器的实例或 `raw()` SQL 片段。

关于迁移的更多内容，请阅读[文档](./37-migrations.md)。

<a id="one-more-entity"></a>
### 再加一个实体

迁移已经配置好了，我们通过再加一个实体来测试它们——`Comment`，它同样属于 article 模块，所以放在 `src/modules/article/comment.entity.ts`。

```ts title='comment.entity.ts'
import { defineEntity, type InferEntity, p } from '@mikro-orm/core';
import { ArticleSchema } from './article.entity.js';
import { UserSchema } from '../user/user.entity.js';
import { BaseSchema } from '../common/base.entity.js';

export const CommentSchema = defineEntity({
  name: 'Comment',
  extends: BaseSchema,
  properties: {
    text: p.string(),
    article: () => p.manyToOne(ArticleSchema).ref(),
    author: () => p.manyToOne(UserSchema).ref(),
  },
});

export type IComment = InferEntity<typeof CommentSchema>;
```

以及 `Article` 实体中的 OneToMany 反向方：

```ts
comments: () => p.oneToMany(CommentSchema).mappedBy('article').eager().orphanRemoval(),
```

别忘了把这个仓库也加入你的简单 DI 容器：

```ts file='db.ts'
export interface Services {
  orm: MikroORM;
  em: EntityManager;
  user: UserRepository;
  article: EntityRepository<IArticle>;
  // highlight-next-line
  comment: EntityRepository<IComment>;
  tag: EntityRepository<ITag>;
}

export function initORM(options?: Partial<Options>): Services {
  // ...

  return cache = {
   orm,
   em: orm.em,
   user: orm.em.getRepository(UserSchema),
   article: orm.em.getRepository(ArticleSchema),
   // highlight-next-line
   comment: orm.em.getRepository(CommentSchema),
   tag: orm.em.getRepository(TagSchema),
  };
}
```

> 这里用到了两个新的构建器方法 `.eager()` 与 `.orphanRemoval()`：
>
> - `.eager()` 会自动填充这个关联，效果就如同你显式使用了 `populate: ['comments']`。
> - `.orphanRemoval()` 是一种特殊的级联：从这类集合中移除的任何实体都会从数据库中被删除，而不仅仅是与关联脱离（把外键设为 `null`）。

现在通过 CLI 创建迁移并运行它。另外，为了测试，不妨也试试其他迁移相关命令：

```bash
# 基于 schema 差异创建新迁移
npx mikro-orm migration:create

# 列出待执行的迁移
npx mikro-orm migration:pending

# 执行待执行的迁移
npx mikro-orm migration:up

# 列出已执行的迁移
npx mikro-orm migration:list
```

你应该会看到类似这样的输出：

```bash
npx mikro-orm migration:create
Migration20220913205718.ts successfully created
```

```bash
npx mikro-orm migration:pending

┌─────────────────────────┐
│ Name              │
├─────────────────────────┤
│ Migration20220913205718 │
└─────────────────────────┘
```

```bash
npx mikro-orm migration:up

Processing 'Migration20220913205718'
Applied 'Migration20220913205718'
Successfully migrated up to the latest version
```

```bash
npx mikro-orm migration:list

┌─────────────────────────┬──────────────────────────┐
│ Name              │ Executed at          │
├─────────────────────────┼──────────────────────────┤
│ Migration20220913202829 │ 2022-09-13T18:57:12.000Z │
│ Migration20220913205718 │ 2022-09-13T18:57:27.000Z │
└─────────────────────────┴──────────────────────────┘
```

:::info 迁移快照

创建新迁移时，会自动把目标 schema 快照保存到 migrations 文件夹中。之后当你尝试创建新迁移时，使用的将是这份快照，而不是当前的数据库 schema。这意味着如果你在执行待执行迁移之前就尝试创建新迁移，仍然能得到正确的 schema diff。

> 快照应当与常规迁移文件一样纳入版本管理。

可以通过 ORM 配置中的 `migrations.snapshot: false` 关闭快照功能。

:::

<a id="running-migrations-automatically"></a>
### 自动运行迁移

在收工之前，我们把运行迁移这件事稍微自动化一下——你可以像使用 `SchemaGenerator` 那样，以编程方式使用 `Migrator`。你希望在应用引导阶段、开始接受连接之前运行它们，因此一个合适的位置是你的 `bootstrap` 函数中、初始化 ORM 之后。

```ts title='app.ts'
export async function bootstrap(port = 3001, migrate = true) {
  const db = initORM();

  if (migrate) {
    // 同步 schema
    await db.orm.migrator.up();
  }

  // ...
}
```

你需要有条件地执行这一步，因为你只想为生产数据库运行迁移，而不是为测试数据库（它们直接使用 `SchemaGenerator` 与 `Seeder`）。在测试用例中调用 `bootstrap()` 函数时，别忘了传入 `false`：

```ts title='utils.ts'
export async function initTestApp(port: number) {
  const { orm } = initORM({ ... });

  await orm.schema.create();
  await orm.seeder.seed(TestSeeder);

  const { app } = await bootstrap(port, false); // <-- 这里

  return app;
}
```

<a id="-checkpoint-3"></a>
## ⛳ 检查点 3

现在你有了 4 个实体、一个带单个 get 端点的可运行 Web 应用，以及针对它的基础测试用例。你还配置好了迁移与种子数据。这就是你此刻的 `app.ts`：

> 这里使用的是内存数据库，是 SQLite 通过特殊数据库名 `:memory:` 提供的特性。

这是本章结束后的 [`app.ts` 文件](https://stackblitz.com/edit/mikro-orm-getting-started-guide-cp-3?file=src%2Fapp.ts)：

<iframe width="100%" height="800" frameborder="0" src="https://stackblitz.com/edit/mikro-orm-getting-started-guide-cp-3?embed=1&ctl=1&view=editor&file=src%2Fapp.ts">
</iframe>
