Skip to content

Commit

Permalink
fixing bug at subRoutes.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
kennyg37 committed Apr 25, 2024
1 parent b7af4f0 commit f24c460
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 10 deletions.
3 changes: 2 additions & 1 deletion backend/src/models/subscribe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export interface ISubscribe extends mongoose.Document {
}

const SubscribeSchema = new mongoose.Schema({
email: { type: String, required: true },
email: { type: String, required: true, unique: true},
subscribedAt: { type: Date, default: Date.now },
subscribed: { type: Boolean, default: false },
},
Expand All @@ -18,6 +18,7 @@ const SubscribeSchema = new mongoose.Schema({
email: ret.email,
subscribedAt: ret.subscribedAt,
subscribed: ret.subscribed,
id: ret._id,
}
}
}
Expand Down
51 changes: 42 additions & 9 deletions backend/src/routes/subRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,31 @@ router.get('/data', async (req: Request, res: Response) => {
});

router.post('/add', async (req: Request, res: Response) => {
const {email} = req.body;
const info = new Sub ({
email,
subscribedAt: Date.now(),
subscribed: true
})
await info.save();
res.json('Subscribed successfully')
})
const { email } = req.body;

if (!email) {
return res.status(400).json({ message: 'Email is required' });
}

try {
const existingSubscription = await Sub.findOne({ email });

if (existingSubscription) {
return res.status(409).json({ message: 'Email is already subscribed' });
}
const info = new Sub({
email,
subscribedAt: Date.now(),
subscribed: true
});
await info.save();
res.json('Subscribed successfully');
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Internal Server Error' });
}
});


router.put('/leave', async (req: Request, res: Response) => {
const { email } = req.body;
Expand All @@ -33,6 +49,23 @@ router.put('/leave', async (req: Request, res: Response) => {
res.status(500).json({ message: 'Internal Server Error' });
}
});
router.delete('/delete/:email', async (req: Request, res: Response) => {
const email = req.params.email;
try {
const foundObject = await Sub.findOne({ email });

if (!foundObject) {
return res.status(404).json({ message: 'Object not found' });
}

await Sub.findByIdAndDelete(foundObject._id);
res.json('Deleted successfully');
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Internal Server Error' });
}
});


// swagger to get all subscribers
/**
Expand Down

0 comments on commit f24c460

Please sign in to comment.