54 lines
1.7 KiB
TypeScript
54 lines
1.7 KiB
TypeScript
import { Router } from 'express';
|
|
import { container } from '../../Application/Services/DIContainer';
|
|
import { logRequest, logError } from '../../Application/Services/Logger';
|
|
import { ContactType } from '../../Domain/Contact/ContactAggregate';
|
|
|
|
const contactRouter = Router();
|
|
|
|
// Public endpoint - anyone can create a contact
|
|
contactRouter.post('/', async (req, res) => {
|
|
try {
|
|
// Get user ID if authenticated (optional)
|
|
const userId = (req as any).user?.userId || null;
|
|
|
|
const { name, email, type, txt } = req.body;
|
|
|
|
// Validate required fields
|
|
if (!name || !email || type === undefined || !txt) {
|
|
return res.status(400).json({
|
|
error: 'Missing required fields: name, email, type, and txt are required'
|
|
});
|
|
}
|
|
|
|
// Validate type
|
|
if (!Object.values(ContactType).includes(Number(type))) {
|
|
return res.status(400).json({
|
|
error: 'Invalid contact type. Must be one of: 0 (Bug), 1 (Problem), 2 (Question), 3 (Sales), 4 (Other)'
|
|
});
|
|
}
|
|
|
|
logRequest('Create contact endpoint accessed', req, res, { name, email, type, userId });
|
|
|
|
const result = await container.createContactCommandHandler.execute({
|
|
name,
|
|
email,
|
|
userid: userId,
|
|
type: Number(type),
|
|
txt
|
|
});
|
|
|
|
logRequest('Contact created successfully', req, res, { contactId: result.id, name, email, type });
|
|
res.status(201).json(result);
|
|
} catch (error) {
|
|
logError('Create contact endpoint error', error as Error, req, res);
|
|
|
|
if (error instanceof Error && error.message.includes('validation')) {
|
|
return res.status(400).json({ error: 'Invalid input data', details: error.message });
|
|
}
|
|
|
|
res.status(500).json({ error: 'Internal server error' });
|
|
}
|
|
});
|
|
|
|
export default contactRouter;
|