]> git.ipfire.org Git - thirdparty/vuejs/pinia.git/commitdiff
test: add example of using multiple stores
authorEduardo San Martin Morote <posva13@gmail.com>
Mon, 25 Nov 2019 15:02:33 +0000 (16:02 +0100)
committerEduardo San Martin Morote <posva13@gmail.com>
Tue, 26 Nov 2019 20:00:07 +0000 (21:00 +0100)
__tests__/pinia/stores/cart.ts [new file with mode: 0644]
__tests__/pinia/stores/combined.ts [new file with mode: 0644]
__tests__/pinia/stores/user.ts [new file with mode: 0644]

diff --git a/__tests__/pinia/stores/cart.ts b/__tests__/pinia/stores/cart.ts
new file mode 100644 (file)
index 0000000..cfd206d
--- /dev/null
@@ -0,0 +1,47 @@
+import { makeStore } from '../../../src'
+import { userStore } from './user'
+
+export const cartStore = makeStore(
+  'cart',
+  () => ({
+    rawItems: [] as string[],
+  }),
+  {
+    items: state =>
+      state.rawItems.reduce((items, item) => {
+        const existingItem = items.find(it => it.name === item)
+
+        if (!existingItem) {
+          items.push({ name: item, amount: 1 })
+        } else {
+          existingItem.amount++
+        }
+
+        return items
+      }, [] as { name: string; amount: number }[]),
+  },
+  {}
+)
+
+export function addItem(name: string) {
+  const store = cartStore.useStore()
+  store.state.rawItems.push(name)
+}
+
+export function removeItem(name: string) {
+  const store = cartStore.useStore()
+  const i = store.state.rawItems.indexOf(name)
+  if (i > -1) store.state.rawItems.splice(i, 1)
+}
+
+export async function purchaseItems() {
+  const cart = cartStore.useStore()
+  const user = userStore.useStore()
+  if (!user.state.name) return
+
+  console.log('Purchasing', cart.items.value)
+  const n = cart.items.value.length
+  cart.state.rawItems = []
+
+  return n
+}
diff --git a/__tests__/pinia/stores/combined.ts b/__tests__/pinia/stores/combined.ts
new file mode 100644 (file)
index 0000000..49e09ef
--- /dev/null
@@ -0,0 +1,2 @@
+// in this file we could import other stores that use one each other
+// while avoiding any recursive import
diff --git a/__tests__/pinia/stores/user.ts b/__tests__/pinia/stores/user.ts
new file mode 100644 (file)
index 0000000..7e6b048
--- /dev/null
@@ -0,0 +1,37 @@
+import { makeStore } from '../../../src'
+
+export const userStore = makeStore(
+  'user',
+  () => ({
+    name: 'Eduardo',
+    isAdmin: true as boolean,
+  }),
+  {},
+  {}
+)
+
+export function logout() {
+  const store = userStore.useStore()
+
+  store.patch({
+    name: '',
+    isAdmin: false,
+  })
+
+  // we could do other stuff like redirecting the user
+}
+
+function apiLogin(a: string, p: string) {
+  if (a === 'ed' && p === 'ed') return Promise.resolve({ isAdmin: true })
+  return Promise.reject(new Error('invalid credentials'))
+}
+
+export async function login(user: string, password: string) {
+  const store = userStore.useStore()
+  const userData = await apiLogin(user, password)
+
+  store.patch({
+    name: user,
+    ...userData,
+  })
+}