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