-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.ts
91 lines (48 loc) · 1.68 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/* IMPORT */
import os from 'node:os';
import path from 'node:path';
import fs from 'stubborn-fs';
import zeptoid from 'zeptoid';
import {MEMORY_DATABASE, TEMPORARY_DATABASE} from './constants';
/* MAIN */
const ensureFileSync = ( filePath: string, content: Uint8Array | string = '' ): void => {
if ( fs.attempt.existsSync ( filePath ) ) return;
const folderPath = path.dirname ( filePath );
try {
ensureFolderSync ( folderPath );
writeFileSync ( filePath, content );
} catch {}
};
const ensureFileUnlinkSync = ( filePath: string ): void => {
return fs.attempt.unlinkSync ( filePath );
};
const ensureFolderSync = ( folderPath: string ): void => {
fs.attempt.mkdirSync ( folderPath, { recursive: true } );
};
const getDatabasePath = ( db: Uint8Array | string ): string => {
if ( db === MEMORY_DATABASE ) {
return db;
} else if ( db === TEMPORARY_DATABASE ) {
return getTempPath ();
} else if ( isUint8Array ( db ) ) {
return getTempPath ( db );
} else {
return path.resolve ( db );
}
};
const getTempPath = ( content?: Uint8Array | string ): string => {
const tempPath = path.join ( os.tmpdir (), `sqlite-${zeptoid ()}.db` );
ensureFileSync ( tempPath, content );
return tempPath;
};
const isUint8Array = ( value: unknown ): value is Uint8Array => {
return value instanceof Uint8Array;
};
const noop = (): void => {
return;
};
const writeFileSync = ( filePath: string, content: Uint8Array | string ): void => {
return fs.retry.writeFileSync ( 1000 )( filePath, content );
};
/* EXPORT */
export {ensureFileSync, ensureFileUnlinkSync, ensureFolderSync, getDatabasePath, getTempPath, isUint8Array, noop, writeFileSync};