-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.js
More file actions
73 lines (62 loc) · 1.74 KB
/
Copy pathstorage.js
File metadata and controls
73 lines (62 loc) · 1.74 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
import { MongoClient, ServerApiVersion } from "mongodb";
import { Capsule } from "./capsule.js";
import dotenv from "dotenv";
dotenv.config();
const uri = process.env.MONGODB_URI;
if (!uri) throw new Error("MONGODB_URI not set");
let collection;
async function connectDB() {
try {
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
tls: true, // <--- Ensure TLS is explicitly enabled
});
await client.connect();
const db = client.db("timecapsule");
collection = db.collection("capsules");
console.log("Connected to MongoDB Atlas");
} catch (err) {
console.error("MongoDB connection failed:", err);
throw err;
}
}
export async function initStorage() {
await connectDB();
}
export class CapsuleStorage {
constructor() {}
async load() {
this.capsules = await collection.find({}).toArray();
}
async addCapsule(capsule) {
const capsuleData = {
id: capsule.id,
message: capsule.message,
unlockDate: capsule.unlockDate.toISOString(),
password: capsule.password,
filePath: capsule.filePath,
createdAt: capsule.createdAt.toISOString(),
};
await collection.insertOne(capsuleData);
}
getCapsuleFromData(data) {
const capsule = new Capsule(
data.message,
data.unlockDate,
data.password,
data.filePath
);
capsule.id = data.id;
capsule.createdAt = new Date(data.createdAt);
return capsule;
}
async getCapsule(id) {
const data = await collection.findOne({ id });
if (!data) return null;
return this.getCapsuleFromData(data);
}
}