第三部分 – 動態處理器

到目前為止,我們已經模擬了兩個 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,但現在我們使用 schema 中的 create 方法來建立新的 Reminder 模型。

現在,如果我們儲存我們的變更並嘗試建立一些提醒事項,我們會看到我們的 POST API 路由成功回應。如果您在主控台中檢查回應,您甚至會看到 Mirage 的資料層已自動為我們為每個新的提醒事項指派自動遞增的 ID。

建立一些提醒事項後,點擊「關於」,然後再次點擊「提醒事項」。您應該會看到您建立的所有提醒事項重新出現!我們已經修復了這個錯誤。

因為我們所有的路由處理器都在讀取和寫入 Mirage 的資料層,我們已經恢復了 API 的參照完整性,並且我們的應用程式的行為就像它在類似生產環境的情況下一樣。

重點

  • Mirage 有一個資料庫,可作為您模擬伺服器資料的單一事實來源
  • 路由處理器應該透過 schema 參數從資料庫讀取和修改資料庫,以便在各個路由處理器之間維護模擬資料的參照完整性