Refactor API types and sync logic
Rename and refactor the types passed over the API to be based on an entity that's either living or a tombstone. A living entity has a deleted property that's either undefined or false, while a tombstone has a deleted property set to true. All entities have a numeric id and an updatedAt timestamp. To sync entities, an array of replacements are passed around. Living entities are replaced with tombstones when they're deleted. And tombstones are replaced with living entities when restored.
This commit is contained in:
parent
251e83f640
commit
fe06d0d6bd
36 changed files with 1242 additions and 834 deletions
|
@ -1,21 +0,0 @@
|
|||
import type { ChangeRecord } from "~/shared/types/schedule";
|
||||
|
||||
export function applyChange<T extends { id: string }>(change: ChangeRecord<T>, data: T[]) {
|
||||
const index = data.findIndex(item => item.id === change.data.id);
|
||||
if (change.op === "del") {
|
||||
if (index !== -1)
|
||||
data.splice(index, 1);
|
||||
} else if (change.op === "set") {
|
||||
if (index !== -1)
|
||||
data.splice(index, 1, change.data);
|
||||
else
|
||||
data.push(change.data)
|
||||
}
|
||||
}
|
||||
|
||||
export function applyChangeArray<T extends { id: string }>(changes: ChangeRecord<T>[], data: T[]) {
|
||||
// Note: quadratic complexity due to findIndex in applyChange
|
||||
for (const change of changes) {
|
||||
applyChange(change, data);
|
||||
}
|
||||
}
|
|
@ -6,6 +6,15 @@ export function* enumerate<T>(iterable: Iterable<T>) {
|
|||
}
|
||||
}
|
||||
|
||||
/** Filters an iterable based on the passed predicate function */
|
||||
export function* filter<T, S extends T>(it: Iterable<T>, predicate: (value: T) => value is S) {
|
||||
for (const value of it) {
|
||||
if (predicate(value)) {
|
||||
yield value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Converts a name to an id */
|
||||
export function toId(name: string) {
|
||||
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-");
|
||||
|
|
14
shared/utils/update.ts
Normal file
14
shared/utils/update.ts
Normal file
|
@ -0,0 +1,14 @@
|
|||
import type { Entity } from "~/shared/types/common";
|
||||
|
||||
export function applyUpdatesToArray<T extends Entity>(updates: T[], entities: T[]) {
|
||||
const idMap = new Map(entities.map((e, i) => [e.id, i]));
|
||||
for (const update of updates) {
|
||||
const index = idMap.get(update.id);
|
||||
if (index !== undefined) {
|
||||
entities[index] = update;
|
||||
} else {
|
||||
idMap.set(update.id, entities.length);
|
||||
entities.push(update);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue