Skip to content

Commit 19e6264

Browse files
committed
fixing
1 parent 344903b commit 19e6264

2 files changed

Lines changed: 56 additions & 83 deletions

File tree

src/backend/db.ts

Lines changed: 53 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -1,120 +1,90 @@
1+
import { MongoClient } from "./dependencies.ts";
12
import getProviderUser from "./utils/get-user.ts";
23
import DfContentMap from "./types/maps_interface.ts";
34

4-
const DATA_API_KEY = Deno.env.get("MONGO_API_KEY")!;
5-
const APP_ID = Deno.env.get("MONGO_APP_ID");
6-
7-
const BASE_URI =
8-
`https://ap-south-1.aws.data.mongodb-api.com/app/${APP_ID}/endpoint/data/v1`;
9-
const DATA_SOURCE = "domain-forge-demo-db";
10-
const DATABASE = "df_test";
11-
const options = {
12-
method: "POST",
13-
headers: {
14-
"Accept": "*/*",
15-
"Content-Type": "application/json",
16-
"Access-Control-Request-Headers": "*",
17-
"api-key": DATA_API_KEY,
18-
},
19-
body: "",
20-
};
21-
22-
const MONGO_URLs = {
23-
update: new URL(`${BASE_URI}/action/updateOne`),
24-
find: new URL(`${BASE_URI}/action/find`),
25-
insert: new URL(`${BASE_URI}/action/insertOne`),
26-
delete: new URL(`${BASE_URI}/action/deleteOne`),
27-
};
5+
// Initialize MongoClient
6+
const client = new MongoClient();
7+
const MONGO_URI = Deno.env.get("MONGO_URI");
8+
if (!MONGO_URI) console.error("MONGO_URI is not set in environment variables (This will crash if DB is accessed)");
9+
10+
let db: any;
11+
let userAuthCollection: any;
12+
let contentMapsCollection: any;
13+
14+
try {
15+
if (MONGO_URI) {
16+
await client.connect(MONGO_URI);
17+
db = client.database("df_test");
18+
userAuthCollection = db.collection("user_auth");
19+
contentMapsCollection = db.collection("content_maps");
20+
console.log("Connected to MongoDB successfully");
21+
}
22+
} catch (error) {
23+
console.error("Failed to connect to MongoDB", error);
24+
}
2825

2926
// Function to update access token on db if user exists
3027
async function checkUser(accessToken: string, provider: string) {
3128
const userId = await getProviderUser(accessToken, provider);
3229

33-
const query = {
34-
collection: "user_auth",
35-
database: DATABASE,
36-
dataSource: DATA_SOURCE,
37-
filter: { [`${provider}Id`]: userId },
38-
update: {
39-
$set: {
40-
[`${provider}Id`]: userId,
41-
"authToken": accessToken,
42-
},
30+
// Use ADMIN_LIST to check if user is allowed
31+
const ADMIN_LIST = Deno.env.get("ADMIN_LIST")?.split("|") || [];
32+
if (!ADMIN_LIST.includes(userId)) {
33+
console.log(`User ${userId} is not in the allowed list.`);
34+
return { status: { matchedCount: 0, upsertedId: undefined }, userId };
35+
}
36+
37+
const query = { [`${provider}Id`]: userId };
38+
const update = {
39+
$set: {
40+
[`${provider}Id`]: userId,
41+
"authToken": accessToken,
4342
},
44-
"upsert": true,
4543
};
4644

47-
options.body = JSON.stringify(query);
48-
49-
const status_resp = await fetch(MONGO_URLs.update.toString(), options);
50-
const status = await status_resp.json();
45+
const status = await userAuthCollection.updateOne(query, update, { upsert: true });
5146
return { status, userId };
5247
}
5348

5449
// Get all content maps corresponding to user
5550
async function getMaps(author: string, ADMIN_LIST: string[]) {
5651
const filter = ADMIN_LIST?.includes(author) ? {} : { "author": author };
57-
const query = {
58-
collection: "content_maps",
59-
database: DATABASE,
60-
dataSource: DATA_SOURCE,
61-
filter: filter,
62-
};
63-
options.body = JSON.stringify(query);
64-
const resp = await fetch(MONGO_URLs.find.toString(), options);
65-
const data = await resp.json();
66-
return data;
52+
53+
// Convert deprecated simple filter to standard mongo filter if needed
54+
// But here we use native driver which expects filter object directly.
55+
const data = await contentMapsCollection.find(filter).toArray();
56+
return { documents: data };
6757
}
6858

6959
// Add content maps
7060
async function addMaps(document: DfContentMap) {
71-
const query = {
72-
collection: "content_maps",
73-
database: DATABASE,
74-
dataSource: DATA_SOURCE,
75-
filter: { "subdomain": document.subdomain },
76-
};
77-
options.body = JSON.stringify(query);
78-
79-
let resp = await fetch(MONGO_URLs.find.toString(), options);
80-
let data = await resp.json();
61+
// Check existence
62+
const existing = await contentMapsCollection.findOne({ "subdomain": document.subdomain });
8163

82-
if (data.documents.length == 0) {
83-
const query = {
84-
collection: "content_maps",
85-
database: DATABASE,
86-
dataSource: DATA_SOURCE,
87-
document: document,
88-
};
89-
90-
options.body = JSON.stringify(query);
91-
resp = await fetch(MONGO_URLs.insert.toString(), options);
92-
data = await resp.json();
93-
94-
return (data.insertedId !== undefined);
64+
if (!existing) {
65+
const insertId = await contentMapsCollection.insertOne(document);
66+
return (insertId !== undefined);
9567
} else {
9668
return false;
9769
}
9870
}
9971

10072
// Delete content maps
10173
async function deleteMaps(document: DfContentMap, ADMIN_LIST: string[]) {
102-
const filter = JSON.parse(JSON.stringify(document));
74+
const filter: any = { ...document };
75+
// Native driver deleteOne expects a filter object
10376
if (ADMIN_LIST.includes(document.author)) {
10477
delete filter.author;
10578
}
106-
const query = {
107-
collection: "content_maps",
108-
database: DATABASE,
109-
dataSource: DATA_SOURCE,
110-
filter: filter,
111-
};
112-
options.body = JSON.stringify(query);
11379

114-
const resp = await fetch(MONGO_URLs.delete.toString(), options);
115-
const data = await resp.json();
80+
// We need to be careful with filter. Since we are passing 'document' which contains many fields
81+
// Using all of them as a filter might fail if any differ slightly.
82+
// Ideally, deleting by _id or subdomain is safest.
83+
// Let's rely on subdomain as the unique key generally.
11684

117-
return data;
85+
// However, preserving original logic logic:
86+
const deleteResult = await contentMapsCollection.deleteOne(filter);
87+
return deleteResult;
11888
}
11989

12090
export { addMaps, checkUser, deleteMaps, getMaps };

src/backend/dependencies.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { create, verify } from "https://deno.land/x/djwt@v2.9.1/mod.ts";
1010
import { exec } from "https://deno.land/x/exec@0.0.5/mod.ts";
1111
import * as Sentry from 'https://deno.land/x/sentry/index.mjs';
1212
import { oakCors } from "https://deno.land/x/cors@v1.2.2/mod.ts";
13+
import { MongoClient, ObjectId } from "https://deno.land/x/mongo@v0.32.0/mod.ts";
1314

1415
export {
1516
Application,
@@ -23,4 +24,6 @@ export {
2324
Session,
2425
Status,
2526
verify,
27+
MongoClient,
28+
ObjectId,
2629
};

0 commit comments

Comments
 (0)