diff --git a/package.json b/package.json index beb1c72..28093f7 100644 --- a/package.json +++ b/package.json @@ -27,11 +27,13 @@ "svelte": "^3.54.0", "svelte-check": "^2.9.2", "vite": "^4.0.0", - "vitest": "^0.25.3" + "vitest": "^0.25.8" }, "type": "module", "dependencies": { "beercss": "^3.0.4", + "dexie": "^3.2.2", + "fake-indexeddb": "^4.0.1", "material-dynamic-colors": "^0.1.5" } } diff --git a/src/lib/store/api.js b/src/lib/store/api.js new file mode 100644 index 0000000..236a607 --- /dev/null +++ b/src/lib/store/api.js @@ -0,0 +1,32 @@ +import Dexie, { liveQuery } from 'dexie'; +import { writable } from 'svelte/store'; + +const seedCampaign = { + battles: [], +}; + +export function genApi(options = {}) { + const storage = new Dexie('Campaigns', options.dexie ?? {}); + + storage.version(1).stores({ + campaigns: '++id,name', + }); + + const campaigns = liveQuery(async () => { + const c = []; + await storage.campaigns + .toCollection() + .each(({ id, name }) => c.push({ id, name })); + return c; + }); + + return { + campaigns, + storage, + event: { + addCampaign: (name) => + storage.campaigns.add({ name, ...seedCampaign }), + deleteCampaign: (id) => storage.campaigns.delete(id), + }, + }; +} diff --git a/src/lib/store/api.test.js b/src/lib/store/api.test.js new file mode 100644 index 0000000..912295d --- /dev/null +++ b/src/lib/store/api.test.js @@ -0,0 +1,28 @@ +import { test, expect } from 'vitest'; +//import { indexedDB, IDBKeyRange } from 'fake-indexeddb'; +import 'fake-indexeddb/auto'; + +import { genApi } from './api.js'; + +const get = async (store) => new Promise((resolve) => store.subscribe(resolve)); + +test('create and add and remove campaigns', async () => { + const api = genApi(); //{ dexie: { indexedDB, IDBKeyRange } }); + + api.event.addCampaign('C1'); + api.event.addCampaign('C2'); + + let result = await get(api.campaigns); + + expect(result).toHaveLength(2); + expect(result[0]).toEqual({ + id: 1, + name: 'C1', + }); + + api.event.deleteCampaign(1); + + result = await get(api.campaigns); + + expect(result).toHaveLength(1); +});