From: Eduardo San Martin Morote Date: Mon, 25 Nov 2019 15:02:33 +0000 (+0100) Subject: test: add example of using multiple stores X-Git-Tag: v0.0.1~4 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=87244f8002da74e28f43a601b042015babf7a4da;p=thirdparty%2Fvuejs%2Fpinia.git test: add example of using multiple stores --- diff --git a/__tests__/pinia/stores/cart.ts b/__tests__/pinia/stores/cart.ts new file mode 100644 index 00000000..cfd206da --- /dev/null +++ b/__tests__/pinia/stores/cart.ts @@ -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 index 00000000..49e09efc --- /dev/null +++ b/__tests__/pinia/stores/combined.ts @@ -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 index 00000000..7e6b048f --- /dev/null +++ b/__tests__/pinia/stores/user.ts @@ -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, + }) +}