Skip to content

Commit 2f9b228

Browse files
committed
Create user route
1 parent 5f900ce commit 2f9b228

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// src/routes/items.ts
2+
import express, { Request, Response } from 'express';
3+
import { Collection } from 'mongodb';
4+
import { connectToDB } from '../db/mongoClient';
5+
import { UserQuestions } from '../models/types';
6+
7+
const router = express.Router();
8+
let questionsCollection: Collection<UserQuestions>;
9+
10+
// Middleware to connect to MongoDB and get the collection
11+
router.use(async (_, res, next) => {
12+
try {
13+
const db = await connectToDB();
14+
questionsCollection = db.collection<UserQuestions>('userQuestions');
15+
next();
16+
} catch (error) {
17+
res.status(500).json({ error: "Failed to connect to MongoDB" });
18+
}
19+
});
20+
21+
// GET all items
22+
router.get('/', async (req: Request, res: Response) => {
23+
try {
24+
const items = await questionsCollection.find().toArray();
25+
res.status(200).json(items);
26+
} catch (error) {
27+
res.status(500).json({ error: "Failed to fetch items" });
28+
}
29+
});
30+
31+
// POST new item
32+
33+
export default router;

0 commit comments

Comments
 (0)