# Coding Convention

This document outlines the coding standards and conventions to be followed in the backend-template-typescript-nodejs project. Adhering to these guidelines ensures code consistency, readability, and maintainability.

## Table of Contents

1. [General Principles](#general-principles)
2. [TypeScript Guidelines](#typescript-guidelines)
3. [File and Folder Structure](#file-and-folder-structure)
4. [Naming Conventions](#naming-conventions)
5. [Code Style](#code-style)
6. [Imports and Exports](#imports-and-exports)
7. [Error Handling](#error-handling)
8. [Testing](#testing)
9. [Documentation](#documentation)
10. [Database Conventions](#database-conventions)
11. [API Generation Guidelines](#api-generation-guidelines)
12. [API Response Guidelines](#api-response-guidelines)
13. [Authentication Guidelines](#authentication-guidelines)
14. [Query Modifier Guidelines](#query-modifier-guidelines)
15. [Git and GitLab Guidelines](#git-and-gitlab-guidelines)

## General Principles

- Write clean, readable, and maintainable code.
- Follow the DRY (Don't Repeat Yourself) principle.
- Use meaningful names for variables, functions, and classes.
- Keep functions small and focused on a single responsibility.
- Comment code when necessary, but prefer self-documenting code.

## TypeScript Guidelines

- Use TypeScript for all new code.
- Enable strict mode in `tsconfig.json`.
- Use interfaces for object types.
- Avoid `any` type; use specific types instead.
- Use union types and generics where appropriate.

## File and Folder Structure

- Follow the existing project structure:
  - `src/` for source code
  - `lib/` for build outputs and utilities
  - `config/` for configuration files
  - `guidelines/` for documentation
- Use kebab-case for file names (e.g., `user-service.ts`).
- Group related files in folders (e.g., `controllers/`, `services/`, `models/`).

## Naming Conventions

- **Variables and Functions**: camelCase (e.g., `userService`, `getUserById`)
- **Classes and Interfaces**: PascalCase (e.g., `UserService`, `IUser`)
- **Constants**: UPPER_SNAKE_CASE (e.g., `MAX_RETRY_COUNT`)
- **Files**: kebab-case (e.g., `user-controller.ts`)
- **Folders**: kebab-case (e.g., `user-management`)

## Code Style

- Use ESLint and Prettier for code formatting and linting.
- Configure them in the project root.
- Maximum line length: 100 characters.
- Use 2 spaces for indentation.
- Use single quotes for strings.
- Add semicolons at the end of statements.

## Imports and Exports

- Use ES6 import/export syntax.
- Group imports: Node.js modules, third-party libraries, local modules.
- Use absolute paths for imports within the project.
- Export only what needs to be public.

## Error Handling

- Use try-catch blocks for synchronous code.
- Use promises or async/await for asynchronous operations.
- Create custom error classes extending the built-in Error class.
- Log errors appropriately using the logging service.

## Testing

- Write unit tests for all functions and classes.
- Use a testing framework like Jest.
- Aim for high code coverage.
- Place test files next to the code they test (e.g., `user-service.test.ts`).

## Tools and Configuration

- **Linting**: ESLint
- **Formatting**: Prettier
- **Testing**: Jest
- **Build**: TypeScript compiler
- **Package Manager**: pnpm

## Database Conventions

- Use PostgreSQL as the primary database.
- Follow naming conventions: snake_case for table and column names (e.g., `user_sessions`).
- Use UUID for primary keys where possible.
- Include timestamps: `created_at`, `updated_at`.
- Use enums for status fields (e.g., user_status).
- Implement foreign key constraints.
- Use indexes on frequently queried columns.
- Store sensitive data encrypted (e.g., passwords with bcrypt).
- Use JSONB for flexible data structures.
- Follow the schema structure in `sql/` folder for auth and other modules.

## API Generation Guidelines

- Use the API generator for automated CRUD and bulk endpoints.
- Commands: `pnpm gen-api <model>` for CRUD, `pnpm gen-api-bulk <model>` for bulk operations.
- Generated endpoints include GET all, POST create, GET by ID, PUT update, DELETE by ID.
- Specify domain, apiPath, and swaggerTag as needed.
- Ensure models exist before generating APIs.
- Customize generated code as necessary after generation.

## API Response Guidelines

- Use GenericError for consistent error handling.
- Support multi-language messages (Vietnamese and English).
- Throw GenericError with message object, type, code, and optional additionalData.
- Use res.error() in catch blocks for automatic formatting.
- Follow unified response format for success and error cases.
- Integrate with Joi validation and database error handlers.

## Authentication Guidelines

- Implement JWT-based authentication with access and refresh tokens.
- Use role-based access control (RBAC) with roles: user, admin, system_admin.
- Admin-only user creation; no self-registration.
- Support 2FA (TOTP, SMS, Email).
- Track user sessions with device info and token versioning.
- Implement password history and security monitoring.
- Use bcrypt for password hashing.
- Log authentication events for audit purposes.
- Follow the database schema in `sql/auth-schema.sql`.

## Query Modifier Guidelines

- Use API Query Modifier to transform array and boolean query parameters.
- Parameters ending with `[]` become arrays; starting with `is_` become booleans.
- Implement Query Modifier for pagination, sorting, and filtering.
- Support query parameters like `page`, `limit`, `sort`, `filter`.
- Use middleware in server.ts for automatic transformation.

## Git and GitLab Guidelines

- Use the company's GitLab for all projects; request account from mentor if needed.
- All names (variables, functions, branches, commits) must be in English.
- Branch naming: Start with `feat/` for new features (e.g., `feat/user-auth`), `fix/` for bug fixes (e.g., `fix/login-error`).
- Commit messages: Follow Conventional Commits format: `<type>(<scope>): <subject>`.
  - Types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`.
  - Subject: <= 50 characters, imperative mood, no period at end.
  - Optional body: Explain why, max ~72 characters per line.
  - Optional footer: Reference issues/tickets.
- Workflow: Clone repo, checkout develop, create feature branch, commit changes, push, create Merge Request (MR) to develop, notify maintainer.
- After merge: Checkout develop, pull, create new branch for next task.

Follow these conventions to maintain code quality across the project. If you have suggestions for improvements, please discuss with the team.
Follow these conventions to maintain code quality across the project. If you have suggestions for improvements, please discuss with the team.

- **Testing**: Jest
- **Build**: TypeScript compiler
- **Package Manager**: pnpm

Follow these conventions to maintain code quality across the project. If you have suggestions for improvements, please discuss with the team.
