-
Notifications
You must be signed in to change notification settings - Fork 3
/
data.ts
108 lines (99 loc) · 2.67 KB
/
data.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
/**
* Abstract RDS (SQL) to entities (Shape, Client).
*/
import { shape } from "../shared/shape";
import { clientState } from "../shared/client-state";
import { must } from "./decode";
import type { ExecuteStatementFn } from "./rds";
import type { Shape } from "../shared/shape";
import type { ClientState } from "../shared/client-state";
export async function getCookieVersion(
executor: ExecuteStatementFn
): Promise<number> {
const result = await executor("SELECT Version FROM Cookie LIMIT 1");
const version = result.records?.[0]?.[0]?.longValue;
if (version === undefined) {
throw new Error("Could not get version field");
}
return version;
}
export async function getLastMutationID(
executor: ExecuteStatementFn,
clientID: string
): Promise<number> {
const result = await executor(
"SELECT LastMutationID FROM Client WHERE Id = :id",
{
id: { stringValue: clientID },
}
);
return result.records?.[0]?.[0]?.longValue ?? 0;
}
export async function setLastMutationID(
executor: ExecuteStatementFn,
clientID: string,
lastMutationID: number
): Promise<void> {
await executor(
"INSERT INTO Client (Id, LastMutationID) VALUES (:id, :lastMutationID) " +
"ON DUPLICATE KEY UPDATE Id = :id, LastMutationID = :lastMutationID",
{
id: { stringValue: clientID },
lastMutationID: { longValue: lastMutationID },
}
);
}
export async function getShape(
executor: ExecuteStatementFn,
id: string
): Promise<Shape | null> {
const { records } = await executor(
"SELECT Content FROM Shape WHERE Id = :id",
{
id: { stringValue: id },
}
);
const content = records?.[0]?.[0]?.stringValue;
if (!content) {
return null;
}
return must(shape.decode(JSON.parse(content)));
}
export async function putShape(
executor: ExecuteStatementFn,
id: string,
shape: Shape
): Promise<void> {
await executor(`CALL PutShape(:id, :content)`, {
id: { stringValue: id },
content: { stringValue: JSON.stringify(shape) },
});
}
export async function getClientState(
executor: ExecuteStatementFn,
id: string
): Promise<ClientState> {
const { records } = await executor(
"SELECT Content FROM ClientState WHERE Id = :id",
{
id: { stringValue: id },
}
);
const content = records?.[0]?.[0]?.stringValue;
if (!content) {
return {
overID: "",
};
}
return must(clientState.decode(JSON.parse(content)));
}
export async function putClientState(
executor: ExecuteStatementFn,
id: string,
clientState: ClientState
): Promise<void> {
await executor(`CALL PutClientState(:id, :content)`, {
id: { stringValue: id },
content: { stringValue: JSON.stringify(clientState) },
});
}