Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add defineStore api #2438

Draft
wants to merge 12 commits into
base: main
Choose a base branch
from
Draft

feat: add defineStore api #2438

wants to merge 12 commits into from

Conversation

kettanaito
Copy link
Member

@kettanaito kettanaito commented Feb 22, 2025

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.
  • 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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant