Repository navigation
Expand file tree
/
Copy pathrecord-history.ts
More file actions
89 lines (77 loc) · 2.03 KB
/
Copy pathrecord-history.ts
File metadata and controls
89 lines (77 loc) · 2.03 KB
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
/**
* Demo program showing how to use the versionstamp to keep track of a record's history
*/
import { deleteAllRecords } from "./util.ts";
interface User {
id: string;
name: string;
age: number;
}
interface Email {
userId: string;
work?: string;
home?: string;
}
interface Version {
versionstamp: string;
date: number;
}
const kv = await Deno.openKv();
async function persistUser(user: User, email: Email) {
const userKey = ["users", user.id];
const emailKey = ["email", user.id];
const kvUser = kv.get(userKey);
const kvEmail = kv.get(emailKey);
const result = await kv.atomic()
.check({
key: (await kvUser).key,
versionstamp: (await kvUser).versionstamp,
})
.check({
key: (await kvEmail).key,
versionstamp: (await kvEmail).versionstamp,
})
.set(userKey, user)
.set(emailKey, email)
.commit();
// Keep track of version in a separate index
if (result.ok) {
await kv.set(["user_versionstamp", userId, result.versionstamp], {
versionstamp: result.versionstamp,
date: new Date().getTime(),
});
}
}
async function displayUserVersions(userId: string) {
console.log(`Version history of user with id ${userId}`);
const iter = kv.list<Version>({ prefix: ["user_versionstamp", userId] }, {
reverse: true,
});
for await (const version of iter) {
// display to stdout here; I'm sure you can do better
console.log(
`Version: ${version.value.versionstamp} Date: ${version.value.date}`,
);
}
}
// Insert the first record
const userId = crypto.randomUUID();
const user: User = {
id: userId,
name: "John Doe",
age: 22,
};
const email: Email = {
userId: userId,
home: "john@doe.com",
work: "jdoe@foobar.com",
};
// insert user and email into primary index
await persistUser(user, email);
// update the user's name and persist user
const newUser = { ...user, name: "Jane Doe" };
await persistUser(newUser, email);
// print out the two user versions
await displayUserVersions(userId);
// get rid of all records
await deleteAllRecords();