Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add mongodb proxy #119

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 159 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,14 @@
"class-variance-authority": "^0.7.0",
"classnames": "^2.5.1",
"clsx": "^2.1.0",
"cors": "^2.8.5",
"dayjs": "^1.11.11",
"decimal.js": "^10.4.3",
"framer-motion": "^11.0.14",
"highlight.js": "^11.9.0",
"install": "^0.13.0",
"lucide-react": "^0.352.0",
"mongodb": "^6.7.0",
"next": "latest",
"next-themes": "^0.2.1",
"node-cache": "latest",
Expand Down Expand Up @@ -93,6 +95,7 @@
"zustand": "^4.5.2"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/node": "^20.11.17",
"@types/prismjs": "^1.26.3",
"@types/react": "^18.2.55",
Expand Down
52 changes: 52 additions & 0 deletions pages/api/mongodb-proxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { NextApiRequest, NextApiResponse } from 'next';
import Cors from 'cors';
import { runMiddleware } from '@/shared/utils/mongodb/middleware';
import { connectToDb } from '@/shared/utils/mongodb/mongo';

// Initialize CORS middleware
const cors = Cors({
methods: ['POST'],
});

export const config = {
api: {
bodyParser: true, // Enable body parsing
},
};

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
await runMiddleware(req, res, cors);

if (req.method !== 'POST') {
res.status(405).json({ message: 'Method Not Allowed' });
return;
}

try {
// Connect to MongoDB and insert data
const db = await connectToDb();
const collection = db.collection('swarms-agent');

const data = req.body;

if (data) {
await collection.insertOne(data);
res.status(201).json({ message: 'Data inserted successfully!' });
} else {
res.status(400).json({ message: 'No data found' });
}
} catch (error) {
console.error('Error inserting data:', error);

if (
error instanceof SyntaxError &&
error.message.includes('Unexpected token')
) {
res.status(400).json({ message: 'Invalid JSON input' });
} else {
res.status(500).json({ message: 'Error processing request' });
}
}
};

export default handler;
16 changes: 16 additions & 0 deletions shared/utils/mongodb/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { NextApiRequest, NextApiResponse } from 'next';

export function runMiddleware(
req: NextApiRequest,
res: NextApiResponse,
fn: Function,
) {
return new Promise((resolve, reject) => {
fn(req, res, (result: unknown) => {
if (result instanceof Error) {
return reject(result);
}
return resolve(result);
});
});
}
22 changes: 22 additions & 0 deletions shared/utils/mongodb/mongo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { MongoClient, Db, ConnectOptions } from 'mongodb';

const uri = process.env.MONGODB_URI as string;

if (!uri) {
throw new Error("Please define the MONGODB_URI environment variable inside .env.local");
}

let client: MongoClient;
let db: Db;

export const connectToDb = async (): Promise<Db> => {
if (!client) {
client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
} as ConnectOptions);
await client.connect();
db = client.db();
}
return db;
};
14 changes: 14 additions & 0 deletions shared/utils/mongodb/upload-data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export const uploadAgentJSONToDB = async (data: any) => {
try {
const response = await fetch('/api/mongodb-proxy', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});

const responseJson = await response.json();
console.log(responseJson);
} catch (error) {
console.error('Error uploading data:', error);
}
};