chore: clean up the patch from yesterday

This commit is contained in:
Paul Makles 2022-03-29 19:23:46 +01:00
parent cf049bd4ee
commit ca240fb6d7

View file

@ -63,7 +63,10 @@ export default class State {
this.sync = new Sync(this); this.sync = new Sync(this);
this.plugins = new Plugins(this); this.plugins = new Plugins(this);
makeAutoObservable(this); makeAutoObservable(this, {
client: false,
});
this.register(); this.register();
this.setDisabled = this.setDisabled.bind(this); this.setDisabled = this.setDisabled.bind(this);
@ -75,6 +78,10 @@ export default class State {
*/ */
private register() { private register() {
for (const key of Object.keys(this)) { for (const key of Object.keys(this)) {
// Skip `client`.
if (key === "client") continue;
// Pull out the relevant object.
const obj = ( const obj = (
this as unknown as Record<string, Record<string, unknown>> this as unknown as Record<string, Record<string, unknown>>
)[key]; )[key];
@ -125,20 +132,26 @@ export default class State {
* @returns Function to dispose of listeners * @returns Function to dispose of listeners
*/ */
registerListeners(client?: Client) { registerListeners(client?: Client) {
// If a client is present currently, expose it and provide it to plugins.
if (client) { if (client) {
this.client = client; this.client = client;
this.plugins.onClient(client); this.plugins.onClient(client);
} }
// Register all the listeners required for saving and syncing state.
const listeners = this.persistent.map(([id, store]) => { const listeners = this.persistent.map(([id, store]) => {
return reaction( return reaction(
() => stringify(store.toJSON()), () => stringify(store.toJSON()),
async (value) => { async (value) => {
try { try {
// Save updated store to local storage.
await localforage.setItem(id, JSON.parse(value)); await localforage.setItem(id, JSON.parse(value));
// Skip if meta store or client not available.
if (id === "sync") return; if (id === "sync") return;
if (!client) return; if (!client) return;
// Generate a new revision and upload changes.
const revision = +new Date(); const revision = +new Date();
switch (id) { switch (id) {
case "settings": { case "settings": {
@ -204,17 +217,10 @@ export default class State {
}); });
return () => { return () => {
// ! FIXME: quick fix // Stop exposing the client.
try { this.client = undefined;
try {
this.client = undefined;
} catch (err) {
reportError(err as any, "state_L207");
}
} catch (err) {
/** just for good measure */
}
// Wipe all listeners.
listeners.forEach((x) => x()); listeners.forEach((x) => x());
}; };
} }