-
Notifications
You must be signed in to change notification settings - Fork 1
/
todo-dwn-repository.ts
120 lines (106 loc) · 2.6 KB
/
todo-dwn-repository.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import { taskDefinition } from "@/protocols/tasks";
import { DwnApi } from "@web5/api";
export interface Task {
id?: string;
title: string;
completed: boolean;
}
export const BLANK_TASK: Task = {
title: "",
completed: false,
};
export class TodoDwnRepository {
constructor(private readonly dwn: DwnApi) {}
async listTasks() {
const records = await this.listTasksRecords();
const tasksJson: Task[] = await Promise.all(
records.map(async (r) => {
const { title, completed } = await r.data.json();
return {
id: r.id,
title,
completed,
};
})
);
return tasksJson.map((r) => ({
id: r.id,
title: r.title,
completed: r.completed,
}));
}
async createTask(task: Task) {
const { status, record } = await this.dwn.records.create({
data: task,
message: {
protocol: taskDefinition.protocol,
protocolPath: "task",
schema: taskDefinition.types.task.schema,
dataFormat: taskDefinition.types.task.dataFormats[0],
published: true,
tags: {
completed: task.completed,
}
},
});
if (status.code !== 202) {
throw Error(status.detail);
}
if (record) {
await record.send();
}
}
async updateTask(task: Task) {
if (!task.id) {
throw new Error("Task ID is required");
}
const record = await this.findTaskRecord(task.id);
if (!record) {
throw new Error("Task not found");
}
const data = { ...task };
delete data.id; // omits record id from data
const { status } = await record.update({
data,
tags: {
completed: task.completed,
}
});
if (status.code !== 202) {
throw Error(status.detail);
}
await record.send();
}
async deleteTask(recordId: string) {
const record = await this.findTaskRecord(recordId);
if (!record) {
throw new Error("Task not found");
}
await record.delete();
return record.send();
}
async findTaskRecord(recordId: string) {
const { record } = await this.dwn.records.read({
protocol: taskDefinition.protocol,
message: {
filter: {
recordId,
},
},
});
return record.id ? record : undefined;
}
async listTasksRecords() {
const { records } = await this.dwn.records.query({
protocol: taskDefinition.protocol,
message: {
filter: {
protocol: taskDefinition.protocol,
protocolPath: "task",
dataFormat: "application/json",
},
},
});
return records || [];
}
}