-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.ts
97 lines (84 loc) · 2.03 KB
/
database.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
/*
Shortener API
GDSC MBCET
*/
import { MongoClient } from "mongo";
import config from "$env";
console.log("Connecting to MongoDB...");
const client = new MongoClient();
const MONGO_URL = new URL(config.MONGO_URI);
if (!MONGO_URL.searchParams.has("authMechanism")) {
MONGO_URL.searchParams.set("authMechanism", "SCRAM-SHA-1");
}
try {
await client.connect(MONGO_URL.href);
} catch (err) {
console.error("Error connecting to MongoDB", err);
throw err;
}
const db = client.database("GDSC-Shortener");
interface URLStorageSchema {
url: string;
hash: string;
createdAt: Date;
clicks: number;
uniqueClicks: number;
ips: string[];
}
const URLStorage = db.collection<URLStorageSchema>("URLStorage");
async function doesHashExist(hash: string) {
const result = await URLStorage.findOne({ hash });
return !!result;
}
async function createShortURL(url: string, hash: string) {
hash = hash.toLowerCase();
if (await doesHashExist(hash)) {
return false;
}
await URLStorage.insertOne({
url,
hash,
createdAt: new Date(),
clicks: 0,
uniqueClicks: 0,
ips: [],
});
return true;
}
async function getURL(hash: string, userIp: string) {
hash = hash.toLowerCase();
const result = await URLStorage.findOne({ hash });
if (!result) return null;
result.clicks++;
if (!result.ips.includes(userIp)) {
result.uniqueClicks++;
result.ips.push(userIp);
}
await URLStorage.updateOne(
{ hash },
{
$set: {
...result,
},
}
);
return result;
}
async function deleteURL(hash: string) {
hash = hash.toLowerCase();
const result = await URLStorage.deleteOne({ hash });
return result;
}
async function getAllURLs() {
const result = await URLStorage.find({}).toArray();
return result;
}
async function editURL(hash: string, url: string) {
hash = hash.toLowerCase();
if (!(await doesHashExist(hash))) {
return false;
}
await URLStorage.updateOne({ hash }, { $set: { url: url } });
return true;
}
export { createShortURL, getURL, deleteURL, getAllURLs, editURL };