← back to Jill Website
src/routes/properties.ts
83 lines
import { Router, Request, Response } from 'express';
import { PropertyModel, Property, PropertyValidationError } from '../models/Property';
// Factory function for testing
export function createPropertiesRouter(propertyModel?: PropertyModel): Router {
const router = Router();
const model = propertyModel || new PropertyModel();
/**
* GET /api/properties
* Get all properties
*/
router.get('/properties', async (req: Request, res: Response): Promise<void> => {
try {
const limit = req.query.limit ? parseInt(req.query.limit as string, 10) : 100;
const offset = req.query.offset ? parseInt(req.query.offset as string, 10) : 0;
const properties = await model.findAll(limit, offset);
res.status(200).json({
success: true,
data: properties,
count: properties.length
});
} catch (error) {
console.error('Error fetching properties:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
message: 'Failed to fetch properties'
});
}
});
/**
* GET /api/properties/:id
* Get property by ID
*/
router.get('/properties/:id', async (req: Request, res: Response): Promise<void> => {
try {
const idParam = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id;
const id = parseInt(idParam, 10);
// Check if the ID is a valid integer (not NaN, not a decimal)
if (isNaN(id) || idParam !== id.toString()) {
res.status(400).json({
success: false,
error: 'Invalid ID',
message: 'Property ID must be a number'
});
return;
}
const property = await model.findById(id);
if (!property) {
res.status(404).json({
success: false,
error: 'Not found',
message: 'Property not found'
});
return;
}
res.status(200).json({
success: true,
data: property
});
} catch (error) {
console.error('Error fetching property:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
message: 'Failed to fetch property'
});
}
});
return router;
}
export default createPropertiesRouter();