-
Notifications
You must be signed in to change notification settings - Fork 0
/
note.server.ts
99 lines (77 loc) · 2.32 KB
/
note.server.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
import cuid from "cuid";
import type { NoteDoc, NewNote } from "./models/note";
import { NoteSchema, NoteDocSchema } from "./models/note";
import { DocType, NoteIdSchema } from "./models/model";
import { NotFoundError } from "./models/err";
import { fromHyper, toHyper } from "./hyper";
import type { NoteServer, ServerContext } from "./types";
export const NotesServerFactory = (env: ServerContext): NoteServer => {
async function getNote({ id }: { id: string }): ReturnType<NoteServer["getNote"]> {
const { hyper } = env;
id = NoteIdSchema.parse(id);
const res = await hyper.data.get(id);
if (!res.ok && res.status === 404) {
return null;
}
return fromHyper.as(NoteSchema)(res);
}
async function getNotesByParent({
parent,
}: {
parent: string;
}): ReturnType<NoteServer["getNotesByParent"]> {
// check hyper cache
const { hyper, UserServer } = env;
const user = await UserServer.getUserById(parent);
if (!user) {
throw new NotFoundError(`parent with id ${parent} not found`);
}
// TODO: use hyper cache to instead of querying db
const res = await hyper.data.query<NoteDoc>({
type: "note",
parent,
});
if (!res.ok) {
throw new Error(res.msg);
}
const { docs } = res;
return docs.map(fromHyper.as(NoteSchema));
}
async function createNote({
body,
title,
parent,
}: NewNote): ReturnType<NoteServer["createNote"]> {
const { hyper, UserServer } = env;
const user = await UserServer.getUserById(parent);
if (!user) {
throw new NotFoundError(`parent with id ${parent} not found`);
}
const newNote = NoteSchema.parse({
id: `note-${cuid()}`,
title,
body,
parent,
});
await hyper.data.add<NoteDoc>(
toHyper.as(NoteDocSchema)({ ...newNote, type: DocType.enum.note })
);
// TODO: invalidate hyper cache for notes from parent
return newNote;
}
async function deleteNote({ id }: { id: string }): ReturnType<NoteServer["deleteNote"]> {
const { hyper } = env;
const note = await getNote({ id });
if (!note) {
throw new NotFoundError();
}
await hyper.data.remove(note.id);
// TODO: invalidate hyper cache for notes from parent
}
return {
getNote,
getNotesByParent,
createNote,
deleteNote,
};
};