-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecondary-index.ts
More file actions
102 lines (92 loc) · 2.16 KB
/
Copy pathsecondary-index.ts
File metadata and controls
102 lines (92 loc) · 2.16 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
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* Demos a one-to-many secondary index
*/
import { deleteAllRecords } from "./util.ts";
type Position = "Goalkeeper" | "Defender" | "Midfielder" | "Forward";
interface Player {
id?: string;
name: string;
position: Position;
}
// Players on the Liverpool Premier League team
const players: Player[] = [
{
"name": "Alisson Becker",
"position": "Goalkeeper",
},
{
"name": "Trent Alexander-Arnold",
"position": "Defender",
},
{
"name": "Virgil van Dijk",
"position": "Defender",
},
{
"name": "Joel Matip",
"position": "Defender",
},
{
"name": "Andrew Robertson",
"position": "Defender",
},
{
"name": "Fabinho",
"position": "Midfielder",
},
{
"name": "Jordan Henderson",
"position": "Midfielder",
},
{
"name": "Harvey Elliot",
"position": "Midfielder",
},
{
"name": "Mohamed Salah",
"position": "Forward",
},
{
"name": "Cody Gakpo",
"position": "Forward",
},
{
"name": "Roberto Firmino",
"position": "Forward",
},
];
// get rid of old records
await deleteAllRecords();
const kv = await Deno.openKv();
// insert players from JSON
for (const player of players) {
const id = crypto.randomUUID();
player.id = id;
const results = await kv.atomic()
.check({ key: ["players", id], versionstamp: null })
.check({
key: ["players_by_position", player.position, player.id],
versionstamp: null,
})
.set(["players", id], player)
.set(["players_by_position", player.position, player.id], player)
.commit();
if (results.ok === false) {
throw new Error(`Problem loading player ${player.name}`);
}
}
const findPlayersByPosition = async (position: Position) => {
const iter = kv.list<Player>({ prefix: ["players_by_position", position] });
for await (const player of iter) {
const playerPosition = await kv.get<Player>([
"players_by_position",
player.value.position,
player.value.id ?? "",
]);
console.log(playerPosition.value?.name);
}
};
// search for various positions
await findPlayersByPosition("Forward");
await findPlayersByPosition("Midfielder");
await findPlayersByPosition("Defender");