-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathflat-to-shard.ts
51 lines (40 loc) · 1.27 KB
/
flat-to-shard.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
import { DirFlat } from './dir-flat.js'
import DirSharded, { type DirShardedOptions } from './dir-sharded.js'
import type { Dir } from './dir.js'
export async function flatToShard (child: Dir | null, dir: Dir, threshold: number, options: DirShardedOptions): Promise<DirSharded> {
let newDir = dir as DirSharded
if (dir instanceof DirFlat && dir.estimateNodeSize() > threshold) {
newDir = await convertToShard(dir, options)
}
const parent = newDir.parent
if (parent != null) {
if (newDir !== dir) {
if (child != null) {
child.parent = newDir
}
if (newDir.parentKey == null) {
throw new Error('No parent key found')
}
await parent.put(newDir.parentKey, newDir)
}
return flatToShard(newDir, parent, threshold, options)
}
return newDir
}
async function convertToShard (oldDir: DirFlat, options: DirShardedOptions): Promise<DirSharded> {
const newDir = new DirSharded({
root: oldDir.root,
dir: true,
parent: oldDir.parent,
parentKey: oldDir.parentKey,
path: oldDir.path,
dirty: oldDir.dirty,
flat: false,
mtime: oldDir.mtime,
mode: oldDir.mode
}, options)
for await (const { key, child } of oldDir.eachChildSeries()) {
await newDir.put(key, child)
}
return newDir
}