-
Notifications
You must be signed in to change notification settings - Fork 36
/
store.ts
55 lines (49 loc) · 1.36 KB
/
store.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
import type {Chunk} from './chunk';
import type {ReadonlyJSONValue} from '../mod';
import type {Hash} from '../hash';
export interface Store {
read(): Promise<Read>;
withRead<R>(fn: (read: Read) => R | Promise<R>): Promise<R>;
write(): Promise<Write>;
withWrite<R>(fn: (Write: Write) => R | Promise<R>): Promise<R>;
close(): Promise<void>;
}
interface GetChunk {
getChunk(hash: Hash): Promise<Chunk | undefined>;
}
export interface Read extends GetChunk {
hasChunk(hash: Hash): Promise<boolean>;
mustGetChunk(hash: Hash): Promise<Chunk>;
getHead(name: string): Promise<Hash | undefined>;
close(): void;
get closed(): boolean;
}
export interface Write extends Read {
createChunk<V extends ReadonlyJSONValue>(
data: V,
refs: readonly Hash[],
): Chunk<V>;
putChunk(c: Chunk): Promise<void>;
setHead(name: string, hash: Hash): Promise<void>;
removeHead(name: string): Promise<void>;
assertValidHash(hash: Hash): void;
commit(): Promise<void>;
}
export class ChunkNotFoundError extends Error {
name = 'ChunkNotFoundError';
readonly hash: Hash;
constructor(hash: Hash) {
super(`Chunk not found ${hash}`);
this.hash = hash;
}
}
export async function mustGetChunk(
store: GetChunk,
hash: Hash,
): Promise<Chunk> {
const chunk = await store.getChunk(hash);
if (chunk) {
return chunk;
}
throw new ChunkNotFoundError(hash);
}