Path: blob/master/src/packages/frontend/app-framework/Table.ts
1503 views
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import { AppRedux } from "../app-framework";6import { bind_methods } from "@cocalc/util/misc";7import { webapp_client } from "../webapp-client";89export type TableConstructor<T extends Table> = new (name, redux) => T;1011export abstract class Table {12public name: string;13public _table: any;14protected redux: AppRedux;1516// override in derived class to pass in options to the query -- these only impact initial query, not changefeed!17options(): any[] {18return [];19}2021abstract query(): void;2223protected abstract _change(table: any, keys: string[]): void;2425protected no_changefeed(): boolean {26return false;27}2829constructor(name, redux) {30bind_methods(this);31this.name = name;32this.redux = redux;33if (this.no_changefeed()) {34// Create the table but with no changefeed.35this._table = webapp_client.sync_client.synctable_no_changefeed(36this.query(),37this.options(),38);39} else {40// Set up a changefeed41this._table = webapp_client.sync_client.sync_table(42this.query(),43this.options(),44);45}4647this._table.on("error", (error) => {48console.warn(`Synctable error (table='${name}'):`, error);49});5051if (this._change != null) {52// Call the _change method whenever there is a change.53this._table.on("change", (keys) => {54this._change(this._table, keys);55});56}57}5859close = () => {60this._table.close();61};6263set = async (64changes: object,65merge?: "deep" | "shallow" | "none", // The actual default is "deep" (see @cocalc/sync/table/synctable.ts)66cb?: (error?: string) => void,67): Promise<void> => {68if (cb == null) {69// No callback, so let async/await report errors.70// Do not let the error silently hide (like using the code below did)!!71// We were missing lot of bugs because of this...72this._table.set(changes, merge);73await this._table.save();74return;75}7677// callback is defined still.78let e: undefined | string = undefined;79try {80this._table.set(changes, merge);81await this._table.save();82} catch (err) {83e = err.toString();84}85cb(e);86};87}888990