-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.ts
More file actions
58 lines (50 loc) · 1.55 KB
/
Copy pathdb.ts
File metadata and controls
58 lines (50 loc) · 1.55 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
import { IGameMetadata, ISerializedGame } from "@craft/engine";
import { Collection, Document, MongoClient } from "mongodb";
export interface IDbManager {
getAllGameMetadata(): Promise<IGameMetadata[]>;
getGame(gameId: string): Promise<ISerializedGame | null>;
saveGame(game: ISerializedGame): Promise<void>;
deleteGame(gameId: string): Promise<void>;
}
export class DBManager implements IDbManager {
static async makeClient() {
const DB_URL = process.env.DB_URL;
if (!DB_URL) {
throw new Error("DB_URL not defined");
}
console.log("Connecting to database");
const client = await MongoClient.connect(DB_URL);
console.log("Connected to database 🎉");
return new DBManager(client);
}
private gameCollection: Collection<Document & ISerializedGame>;
private constructor(private client: MongoClient) {
this.gameCollection = this.client.db("games").collection("games");
}
getAllGameMetadata(): Promise<IGameMetadata[]> {
return this.gameCollection
.find<ISerializedGame>(
{},
{
projection: {
gameId: 1,
name: 1,
},
}
)
.toArray();
}
getGame(gameId: string): Promise<ISerializedGame | null> {
return this.gameCollection.findOne<ISerializedGame>({ gameId });
}
async saveGame(game: ISerializedGame) {
await this.gameCollection.updateOne(
{ gameId: game.gameId },
{ $set: game },
{ upsert: true }
);
}
async deleteGame(gameId: string) {
await this.gameCollection.deleteOne({ gameId });
}
}