---
description: Backend Guidelines
globs: api/**/*.ts
alwaysApply: false
---

# Backend Guidelines

- Always validate API inputs before processing requests.
- Use async/await consistently; avoid callbacks.
- Follow RESTful API conventions for clear endpoint structures.
- Optimize database queries for performance and scalability.
- Log errors properly but avoid excessive debugging logs in production.

## Example:
```ts
// ✅ Good
export const getUserById = async (req: Request, res: Response) => {
  try {
    // Validate input
    const { id } = req.params;
    if (!id || typeof id !== 'string') {
      return res.status(400).json({ error: 'Invalid user ID' });
    }

    // Process request
    const user = await userService.findById(id);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    return res.status(200).json(user);
  } catch (error) {
    console.error('Error fetching user:', error);
    return res.status(500).json({ error: 'Internal server error' });
  }
};

// ❌ Avoid
export function getUser(req, res) {
  const id = req.params.id;
  userService.findById(id, function(err, user) {
    if (err) {
      console.log('Error:', err);
      res.status(500).send('Error');
      return;
    }
    if (user) {
      res.send(user);
    } else {
      res.status(404).send('Not found');
    }
  });
} 