UNPKG

@furystack/core

Version:
51 lines 1.61 kB
import { defineService } from '@furystack/inject'; import { isAsyncDisposable, isDisposable } from '@furystack/utils'; /** * Defines a physical store as a first-class DI token. * * Equivalent to {@link defineService} with a singleton lifetime, with two * additions: * * - The returned token carries `model` and `primaryKey` metadata, so callers * can rebuild queries or DataSets from the token alone. * - The factory installs an {@link ServiceContext.onDispose} hook that * automatically disposes the store (sync or async) when the owning injector * is disposed. * * @example * ```ts * export const UserStore = defineStore({ * name: 'my-app/UserStore', * model: User, * primaryKey: 'username', * factory: () => new InMemoryStore({ model: User, primaryKey: 'username' }), * }) * * const store = injector.get(UserStore) * ``` */ export const defineStore = (options) => { const token = defineService({ name: options.name, lifetime: 'singleton', factory: (ctx) => { const store = options.factory(ctx); ctx.onDispose(async () => { if (isAsyncDisposable(store)) { await store[Symbol.asyncDispose](); return; } if (isDisposable(store)) { store[Symbol.dispose](); } }); return store; }, }); const result = Object.assign(token, { model: options.model, primaryKey: options.primaryKey, }); return result; }; //# sourceMappingURL=define-store.js.map