Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/conat/persist/context.ts
1453 views
1
/*
2
Define functions for using sqlite, the filesystem, compression, etc.
3
These are functions that typically get set via nodejs on the backend,
4
not from a browser. Making this explicit helps clarify the dependence
5
on the backend and make the code more unit testable.
6
*/
7
8
import type BetterSqlite3 from "better-sqlite3";
9
type Database = BetterSqlite3.Database;
10
export { type Database };
11
12
let betterSqlite3: any = null;
13
14
export let compress: (data: Buffer) => Buffer = () => {
15
throw Error("must initialize persist context");
16
};
17
18
export let decompress: (data: Buffer) => Buffer = () => {
19
throw Error("must initialize persist context");
20
};
21
22
export let syncFiles = { local: "", archive: "" };
23
24
export let ensureContainingDirectoryExists: (path: string) => Promise<void> = (
25
_path,
26
) => {
27
throw Error("must initialize persist context");
28
};
29
30
export function initContext(opts: {
31
betterSqlite3;
32
compress: (Buffer) => Buffer;
33
decompress: (Buffer) => Buffer;
34
syncFiles: { local: string; archive: string };
35
ensureContainingDirectoryExists: (path: string) => Promise<void>;
36
}) {
37
betterSqlite3 = opts.betterSqlite3;
38
compress = opts.compress;
39
decompress = opts.decompress;
40
syncFiles = opts.syncFiles;
41
ensureContainingDirectoryExists = opts.ensureContainingDirectoryExists;
42
}
43
44
export function createDatabase(...args): Database {
45
if (betterSqlite3 == null) {
46
throw Error(
47
"conat/persist must be initialized with the better-sqlite3 module -- import from backend/conat/persist instead",
48
);
49
}
50
return new betterSqlite3(...args);
51
}
52
53