パート 4 – シーズ

GET および POST ルート ハンドラーを修正しましたが、アプリは最初は空の状態です。 seeds フックを使用して、Mirage に初期データをシードできます。

これらの行をサーバー定義にコピーします

import { createServer, Model } from "miragejs"

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

    seeds(server) {
      server.create("reminder", { text: "Walk the dog" })
      server.create("reminder", { text: "Take out the trash" })
      server.create("reminder", { text: "Work out" })
    },

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

保存すると、アプリがこれらの 3 つのリマインダーを初期データとしてリロードされるはずです。

server.create 関数を使用すると、Mirage のデータレイヤーに新しいリマインダーを作成できます。ルートハンドラーでreminders.create()を呼び出す場合と同様に、ID は自動的に割り当てられます。

アプリを使用して 4 番目のリマインダーとして「食料品の購入」を作成してみてください。レスポンスを調べると、新しいリマインダーに ID 4 が付いているはずです。また、「About」ページに移動して戻ると、予想どおり 4 つすべてのリマインダーが表示されます。

Mirage のシードは初期化時にロードされ、ブラウザでアプリを操作するときにルート ハンドラーから作成または変更されたデータと並行して動作するため、すべての API データの一貫性が保たれます。

まとめ

  • seeds フックと server.create を使用して、サーバーの初期データを作成します