-
Notifications
You must be signed in to change notification settings - Fork 209
/
Copy pathdeleteRecord.ts
37 lines (28 loc) · 1.28 KB
/
deleteRecord.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { Table } from "@latticexyz/config";
import { Key, Stash } from "../common";
import { encodeKey } from "./encodeKey";
import { registerTable } from "./registerTable";
export type DeleteRecordArgs<table extends Table = Table> = {
stash: Stash;
table: table;
key: Key<table>;
};
export type DeleteRecordResult = void;
export function deleteRecord<table extends Table>({ stash, table, key }: DeleteRecordArgs<table>): DeleteRecordResult {
const { namespaceLabel, label } = table;
if (stash.get().config[namespaceLabel] == null) {
registerTable({ stash, table });
}
const encodedKey = encodeKey({ table, key });
const prevRecord = stash.get().records[namespaceLabel][label][encodedKey];
// Early return if this record doesn't exist
if (prevRecord == null) return;
// Delete record
delete stash._.state.records[namespaceLabel][label][encodedKey];
// Notify table subscribers
const updates = { [encodedKey]: { prev: prevRecord && { ...prevRecord }, current: undefined } };
stash._.tableSubscribers[namespaceLabel][label].forEach((subscriber) => subscriber(updates));
// Notify stash subscribers
const storeUpdate = { config: {}, records: { [namespaceLabel]: { [label]: updates } } };
stash._.storeSubscribers.forEach((subscriber) => subscriber(storeUpdate));
}