CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

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