第 3 部分 - 动态处理程序

到目前为止,我们已经模拟了两个 API 路由,但我们遇到了一个问题。

尝试保存一个新的提醒 "购买杂货",然后点击标题栏中的 "关于" 链接,再点击 "提醒" 返回首页。

最初的三个提醒将重新加载,但你创建的新提醒不在列表中。

Failing

这是因为我们的 GET 处理程序目前是静态的,并且每次运行时都会返回相同的三个硬编码提醒。

this.get("/api/reminders", () => ({
  reminders: [
    { id: 1, text: "Walk the dog" },
    { id: 2, text: "Take out the trash" },
    { id: 3, text: "Work out" },
  ],
}))

我们破坏了应用程序数据的引用完整性,它不再与我们的生产 API 具有相同的行为方式。

让我们使用 Mirage 的数据层来解决这个问题。

我们将从定义一个 Reminder 模型开始,它将告诉 Mirage 为我们在其内存数据库中创建一个 reminders 集合。

import { createServer, Model } from "miragejs"

export default function () {
  createServer({
    models: {
      reminder: Model,
    },

    routes() {
      this.get("/api/reminders", () => ({
        reminders: [
          { id: 1, text: "Walk the dog" },
          { id: 2, text: "Take out the trash" },
          { id: 3, text: "Work out" },
        ],
      }))

      let newId = 4
      this.post("/api/reminders", (schema, request) => {
        let attrs = JSON.parse(request.requestBody)
        attrs.id = newId++

        return { reminder: attrs }
      })
    },
  })
}

现在,我们可以更新我们的 GET 路由处理程序,以便在请求时返回数据库中的所有提醒 - 就像一个真正的服务器一样。

import { createServer, Model } from "miragejs"

export default function () {
  createServer({
    models: {
      reminder: Model,
    },

    routes() {
      this.get("/api/reminders", (schema) => {
        return schema.reminders.all()
      })

      let newId = 4
      this.post("/api/reminders", (schema, request) => {
        let attrs = JSON.parse(request.requestBody)
        attrs.id = newId++

        return { reminder: attrs }
      })
    },
  })
}

schema 参数(它是传递给所有路由处理程序的第一个参数)是与 Mirage 数据层交互的主要方式。

保存并重新加载应用程序后,你应该再次看到 "全部完成!" 消息。这是因为 Mirage 的数据库最初是空的。

接下来,让我们更新 POST 处理程序,以便在 Mirage 的数据层中创建新的 Reminder 模型。

import { createServer, Model } from "miragejs"

export default function () {
  createServer({
    models: {
      reminder: Model,
    },

    routes() {
      this.get("/api/reminders", (schema) => {
        return schema.reminders.all()
      })

      this.post("/api/reminders", (schema, request) => {
        let attrs = JSON.parse(request.requestBody)

        return schema.reminders.create(attrs)
      })
    },
  })
}

在这里,我们像以前一样从请求中获取 attrs,但现在我们使用来自 schemacreate 方法来创建新的 Reminder 模型。

现在,如果我们保存更改并尝试创建一些提醒,我们将看到 POST API 路由成功响应。如果你在控制台中检查响应,你甚至会看到 Mirage 的数据层已经为我们自动为每个新提醒分配了自动递增的 ID。

创建一些提醒后,点击 "关于",然后再次点击 "提醒"。你应该看到你创建的所有提醒都重新出现了!我们已经修复了 bug。

由于我们所有的路由处理程序都从 Mirage 的数据层读取和写入数据,因此我们恢复了 API 的引用完整性,并且我们的应用程序的行为就像在生产环境中一样。

要点

  • Mirage 拥有一个数据库,作为模拟服务器数据的单一事实来源。
  • 路由处理程序应该通过 schema 参数从数据库读取和修改数据,以便在各个路由处理程序之间保持模拟数据的引用完整性。