Open History to see the last commit
1import * as Schema from "effect/Schema";
2
3import { decodeIncomingShareDraft, type IncomingShareDraft } from "./incoming-share-model";
4
5const INCOMING_SHARE_DIRECTORY = "incoming-shares";
6
7export class IncomingShareStorageError extends Schema.TaggedErrorClass<IncomingShareStorageError>()(
8 "IncomingShareStorageError",
9 {
10 operation: Schema.Literals(["load", "write", "remove"]),
11 shareId: Schema.NullOr(Schema.String),
12 cause: Schema.Defect(),
13 },
14) {
15 override get message(): string {
16 return `Incoming share storage operation ${this.operation} failed for ${this.shareId ?? "unknown"}.`;
17 }
18}
19
20function fileName(shareId: string): string {
21 return `${encodeURIComponent(shareId)}.json`;
22}
23
24async function getDirectory() {
25 const { Directory, Paths } = await import("expo-file-system");
26 const directory = new Directory(Paths.document, INCOMING_SHARE_DIRECTORY);
27 directory.create({ idempotent: true, intermediates: true });
28 return directory;
29}
30
31async function getFile(shareId: string) {
32 const { File } = await import("expo-file-system");
33 return new File(await getDirectory(), fileName(shareId));
34}
35
36export async function loadIncomingShareDrafts(): Promise<ReadonlyArray<IncomingShareDraft>> {
37 try {
38 const { File } = await import("expo-file-system");
39 const drafts: IncomingShareDraft[] = [];
40 for (const entry of (await getDirectory()).list()) {
41 if (!(entry instanceof File) || !entry.name.endsWith(".json")) {
42 continue;
43 }
44 try {
45 drafts.push(decodeIncomingShareDraft(JSON.parse(await entry.text()) as unknown));
46 } catch (cause) {
47 console.warn(
48 "[incoming-share] ignored invalid persisted share",
49 new IncomingShareStorageError({ operation: "load", shareId: null, cause }),
50 );
51 }
52 }
53 return drafts.sort((left, right) => right.createdAt.localeCompare(left.createdAt));
54 } catch (cause) {
55 throw new IncomingShareStorageError({ operation: "load", shareId: null, cause });
56 }
57}
58
59export async function writeIncomingShareDraft(draft: IncomingShareDraft): Promise<void> {
60 try {
61 const file = await getFile(draft.id);
62 if (!file.exists) {
63 file.create({ intermediates: true, overwrite: true });
64 }
65 file.write(JSON.stringify(draft));
66 } catch (cause) {
67 throw new IncomingShareStorageError({ operation: "write", shareId: draft.id, cause });
68 }
69}
70
71export async function removeIncomingShareDraft(shareId: string): Promise<void> {
72 try {
73 const file = await getFile(shareId);
74 if (file.exists) {
75 file.delete();
76 }
77 } catch (cause) {
78 throw new IncomingShareStorageError({ operation: "remove", shareId, cause });
79 }
80}