Querying
Target records with queries and logical operators.
Create a collection, seed it with records, and query them.
Add @msw/data as a dependency to your project:
npm install @msw/data --save-devpnpm add @msw/data --save-devYou start by defining a data collection. A collection holds records of the same shape, described by a schema.
import { Collection } from '@msw/data'
import { z } from 'zod'
const users = new Collection({
schema: z.object({
id: z.number(),
name: z.string(),
}),
})Above, we are using Zod to describe the
schemafor the users collection. You can use whichever Standard Schema compliant library of your choice instead.
Next, let's put some values into the collection. Those values are called records. Create individual records via the .create() method or a bunch of them with .createMany():
await users.create({ id: 1, name: 'John' })
await users.createMany(5, (index) => ({
id: index + 1,
name: faker.person.firstName(),
}))Combine
.createMany()with tools like Faker for random values in your records.
From this point on, you can use the users collection for anything data-related: create more records, query them, define relations to other collections, update and delete records.
const john = users.findFirst((q) => q.where({ name: 'John' }))Learn more about what you can do with the library in the following sections: