Path: blob/master/src/packages/conat/persist/context.ts
1710 views
/*1Define functions for using sqlite, the filesystem, compression, etc.2These are functions that typically get set via nodejs on the backend,3not from a browser. Making this explicit helps clarify the dependence4on the backend and make the code more unit testable.5*/67import type BetterSqlite3 from "better-sqlite3";8type Database = BetterSqlite3.Database;9export { type Database };1011let betterSqlite3: any = null;1213export let compress: (data: Buffer) => Buffer = () => {14throw Error("must initialize persist context");15};1617export let decompress: (data: Buffer) => Buffer = () => {18throw Error("must initialize persist context");19};2021export let syncFiles = {22local: "",23archive: "",24archiveInterval: 30_000,25backup: "",26};2728export let ensureContainingDirectoryExists: (path: string) => Promise<void> = (29_path,30) => {31throw Error("must initialize persist context");32};3334export let statSync = (_path: string): { mtimeMs: number } => {35throw Error("must initialize persist context");36};3738export let copyFileSync = (_src: string, _desc: string): void => {39throw Error("must initialize persist context");40};4142export function initContext(opts: {43betterSqlite3;44compress: (Buffer) => Buffer;45decompress: (Buffer) => Buffer;46syncFiles: {47local: string;48archive: string;49archiveInterval: number;50backup: string;51};52ensureContainingDirectoryExists: (path: string) => Promise<void>;53statSync: (path: string) => { mtimeMs: number };54copyFileSync: (src: string, desc: string) => void;55}) {56betterSqlite3 = opts.betterSqlite3;57compress = opts.compress;58decompress = opts.decompress;59syncFiles = opts.syncFiles;60ensureContainingDirectoryExists = opts.ensureContainingDirectoryExists;61statSync = opts.statSync;62copyFileSync = opts.copyFileSync;63}6465export function createDatabase(...args): Database {66if (betterSqlite3 == null) {67throw Error(68"conat/persist must be initialized with the better-sqlite3 module -- import from backend/conat/persist instead",69);70}71return new betterSqlite3(...args);72}737475