Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/conat/persist/context.ts
1710 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 = {
23
local: "",
24
archive: "",
25
archiveInterval: 30_000,
26
backup: "",
27
};
28
29
export let ensureContainingDirectoryExists: (path: string) => Promise<void> = (
30
_path,
31
) => {
32
throw Error("must initialize persist context");
33
};
34
35
export let statSync = (_path: string): { mtimeMs: number } => {
36
throw Error("must initialize persist context");
37
};
38
39
export let copyFileSync = (_src: string, _desc: string): void => {
40
throw Error("must initialize persist context");
41
};
42
43
export function initContext(opts: {
44
betterSqlite3;
45
compress: (Buffer) => Buffer;
46
decompress: (Buffer) => Buffer;
47
syncFiles: {
48
local: string;
49
archive: string;
50
archiveInterval: number;
51
backup: string;
52
};
53
ensureContainingDirectoryExists: (path: string) => Promise<void>;
54
statSync: (path: string) => { mtimeMs: number };
55
copyFileSync: (src: string, desc: string) => void;
56
}) {
57
betterSqlite3 = opts.betterSqlite3;
58
compress = opts.compress;
59
decompress = opts.decompress;
60
syncFiles = opts.syncFiles;
61
ensureContainingDirectoryExists = opts.ensureContainingDirectoryExists;
62
statSync = opts.statSync;
63
copyFileSync = opts.copyFileSync;
64
}
65
66
export function createDatabase(...args): Database {
67
if (betterSqlite3 == null) {
68
throw Error(
69
"conat/persist must be initialized with the better-sqlite3 module -- import from backend/conat/persist instead",
70
);
71
}
72
return new betterSqlite3(...args);
73
}
74
75