Skip to content

Commit

Permalink
chore: wip
Browse files Browse the repository at this point in the history
  • Loading branch information
mzkmnk committed Jan 12, 2025
1 parent 050b95a commit a61ac2c
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,36 @@ export type IndexDBModel<Table extends string> = {
sync?: boolean;
prefix?: string;
nodes: TNodeItem[];
writeCallback: Partial<{
[key in Table]: ({
db,
key,
targetState,
}: { db: Dexie; key: string; targetState: unknown }) => Promise<void>;
}>;
stores: { [key in Table]: string };
};

export const baseWriteCallback = async (
db: Dexie,
key: string,
targetState: unknown,
) => {
if (Array.isArray(targetState)) {
await db.table(key).bulkPut(targetState);
return;
}

await db.table(key).put(targetState);
};

export function withIndexDBSync<Table extends string>({
dbName,
version = 1,
sync = true,
nodes = [],
prefix = '',
writeCallback,
stores,
}: IndexDBModel<Table>) {
const db = new Dexie(dbName);
Expand All @@ -45,10 +66,17 @@ export function withIndexDBSync<Table extends string>({
currentState,
nodes,
prefix,
async (key, fullKeyPath, objectState) => {
await db
.table(fullKeyPath)
.add((objectState as Record<string, unknown>)[key]);
async (key, _fullKeyPath, objectState) => {
const targetState = (objectState as Record<string, unknown>)[
key
];

if (Object.hasOwn(writeCallback, key)) {
// fixme key type check
await writeCallback[key as Table]?.({ db, key, targetState });
} else {
await baseWriteCallback(db, key, targetState);
}
},
);
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ const UserSignalStore = signalStore(
withIndexDBSync<'users' | 'tasks'>({
dbName: 'withIndexDBSync',
nodes: ['users', 'tasks'],
writeCallback: {
users: async ({ db, key, targetState }) => {},
},
stores: {
users: '++id',
tasks: '++id, title, subTitle',
Expand Down

0 comments on commit a61ac2c

Please sign in to comment.