msw icon indicating copy to clipboard operation
msw copied to clipboard

feat: add `defineStore` api

Open kettanaito opened this issue 1 year ago • 0 comments

This is an exploration of a data persistence layer in MSW with input validation on top of Standard schema.

Proposal

import { defineStore } from 'msw'

const store = defineStore({
  collections: {
    // Use Standard Schema so users can define
    // their collections using their schema library of choice.
    post: z.object({
      id: z.string(),
      title: z.string()
    })
  }
})

const server = setupServer()
server.listen({ context: { store } })

server.use(
  http.get('/posts/:id', async ({ params, store }) => {
    // Get a record by its ID.
    const posts = await store.open('posts')
    const post = await posts.get(params.id)
    return HttpResponse.json(post)
  })
)
  • All store and Collection methods must be asynchronous to accommodate any future changes in regards to how records are created or persisted.

What about @mswjs/data?

This proposal has no goal to implement a querying system. I have found those to be redundant and overly-complex for everyone. Instead, use simple predicates, simple update functions.

This is likely to deprecate @mswjs/data. This proposal solves a bunch of long-requested features, such as schema support and type-safety.

This proposal will not support relations. But I suspect you can express relations between objects in schema libraries maybe?

Roadmap

  • [ ] Persistence. localStorage since it exists everywhere (check Node.js 18).
    • Nope, not a thing in Node.js. May be available in more recent releases.
  • [x] Support context: { store } extension on server.listen() and worker.listen().
    • Consider moving this out and implementing as a separate feature. Store doesn't need this to work. This is purely a quality-of-life thing.
  • [ ] Tests. More tests!

kettanaito avatar Feb 22 '25 12:02 kettanaito