NestJS Coding Guidelines
These guidelines aim to establish best practices for writing clean, maintainable, and efficient code in NestJS applications.
Table of Contents
- File and Folder Structure
- Naming Conventions
- Code Formatting
- Error Handling
- Dependency Injection
- Testing
- Documentation
- Security Considerations
- Performance Optimization
1. File and Folder Structure
- Follow NestJS Recommended Structure: Stick to the default structure recommended by NestJS to maintain consistency across projects.
- Group Related Files: Group files by feature or functionality, such as modules, controllers, services, etc.
- Descriptive Naming: Use descriptive and meaningful names for folders and files to improve readability and maintainability.
- Avoid Deep Nesting: Keep the folder structure as flat as possible to avoid deep nesting, which can make navigation more complex.
2. Naming Conventions
- Descriptive Naming: Use meaningful and descriptive names for variables, functions, classes, etc. This improves code readability.
- Follow TypeScript Naming Conventions: Adhere to TypeScript naming conventions for consistency. For example, camelCase for variables and functions, PascalCase for classes, and UPPER_CASE for constants.
- Prefix Convention: Prefix classes with identifiers such as
Service,Controller,Module, etc., to easily identify their purpose.
3. Code Formatting
- Consistent Indentation: Use consistent indentation (e.g., 2 or 4 spaces) throughout the project.
- Line Length: Limit lines to 80-120 characters to enhance readability, particularly when viewing code in various editors or terminals.
- String Quotes: Prefer single quotes for string literals unless interpolation of values is needed.
- Remove Trailing Whitespaces: Ensure that there are no trailing whitespaces at the end of lines.
- Meaningful Comments: Use comments to explain complex logic, algorithms, or important decisions. Keep them concise and meaningful.
- DRY Principle: Follow the DRY (Don't Repeat Yourself) principle to avoid code duplication and promote maintainability.
4. Error Handling
- Graceful Error Handling: Handle errors gracefully to prevent crashing and ensure a smooth user experience.
- Use Built-in Features: Utilize NestJS built-in exception filters and pipes for handling errors effectively.
- Centralize Error Handling: Centralize error handling logic where appropriate, especially for common error scenarios.
- Logging: Log errors with sufficient context (e.g., error message, stack trace, request context) for easier debugging and troubleshooting.
5. Dependency Injection
- Leverage Dependency Injection: Utilize NestJS' powerful dependency injection system to manage dependencies efficiently.
- Avoid Manual Instantiation: Avoid using the
newkeyword to instantiate classes manually. Instead, rely on dependency injection for creating instances. - Keep Dependencies Minimal: Aim to keep the dependencies of a class or module minimal to improve maintainability and testability.
- Constructor Injection: Prefer constructor injection over property injection for injecting dependencies into classes.
6. Testing
- Comprehensive Unit Tests: Write comprehensive unit tests for all services, controllers, and other logic using a testing framework like Jest.
- Test Cases: Include test cases for both success and failure scenarios to ensure robustness and reliability.
- Mocking Dependencies: Mock external dependencies in unit tests to isolate the unit under test and prevent side effects.
- Automated Testing: Automate the execution of tests using continuous integration (CI) tools for early detection of bugs.
7. Documentation
- API Documentation: Document all public APIs (e.g., controllers, services) using JSDoc comments to provide clear and concise information about their purpose, parameters, return values, and potential side effects.
- Usage Examples: Include usage examples and code snippets to demonstrate how to use each API effectively.
- Assumptions and Constraints: Document any assumptions or constraints related to the APIs to guide users and developers.
8. Security Considerations
- Input Validation: Always validate input data to prevent common security vulnerabilities such as injection attacks (e.g., SQL injection, XSS).
- Authentication and Authorization: Implement robust authentication and authorization mechanisms to protect sensitive resources and endpoints.
- Secure Communication: Use HTTPS and other secure communication protocols to encrypt data transmitted over the network.
- Data Sanitization: Sanitize user input and data to prevent malicious content from causing security breaches.
- Third-party Dependencies: Be cautious when using third-party dependencies and libraries, ensuring they are regularly updated and free from known vulnerabilities.
9. Performance Optimization
- Query Optimization: Optimize database queries to reduce response times and improve overall application performance.
- Caching: Utilize caching mechanisms (e.g., Redis, in-memory caching) to cache frequently accessed data and reduce database load.
- Asynchronous Operations: Use asynchronous operations (e.g., async/await, Promises) for I/O-bound tasks to improve concurrency and responsiveness.
- Code Profiling: Profile application code regularly to identify performance bottlenecks and optimize critical sections.
- Resource Management: Dispose of resources (e.g., database connections, file handles) properly to avoid memory leaks and resource exhaustion.
Additional Resources
These guidelines should be followed to ensure consistency, maintainability, and security across NestJS projects. They are not exhaustive and should be adapted based on specific project requirements and industry best practices.