-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdurableBase.ts
87 lines (78 loc) · 1.82 KB
/
durableBase.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
export type Durable = Map<any, any> | Set<any>;
export function defaultEncoder(line: string) {
return line;
}
export function defaultDecoder(line: string) {
return line;
}
export const defaultSeparator = "\n";
export const defaultMode = 0o600;
export async function readLog(
filename: string,
lineDecoder: Function,
decode: Function,
separator: string,
object: any,
): Promise<void> {
try {
const encodedLog = await Deno.readTextFile(filename);
const lines = encodedLog.split(separator);
for (const encoded of lines) {
if (encoded.length > 0) {
lineDecoder(decode(encoded), object, filename);
}
}
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
return;
}
throw err;
}
return;
}
export function writeData(
filename: string,
mode: number,
encode: Function,
separator: string,
data: any,
): void {
const encoded = encode(JSON.stringify(data)) + separator;
const opts = {
mode,
append: true,
};
Deno.writeTextFileSync(filename, encoded, opts);
}
export async function deleteFileIfExists(filename: string): Promise<void> {
try {
await Deno.remove(filename);
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
}
}
export async function compact(
filename: string,
mode: number,
encode: Function,
separator: string,
cmd: string,
object: Durable,
): Promise<void> {
const tmpFile = `${filename}~`;
await deleteFileIfExists(tmpFile);
if (object instanceof Set) {
for (const key of object.keys()) {
writeData(tmpFile, mode, encode, separator, { cmd, key });
}
} else {
for (const [key, value] of object.entries()) {
writeData(tmpFile, mode, encode, separator, { cmd, key, value });
}
}
if (object.size) {
Deno.renameSync(tmpFile, filename);
}
}