# API Response Standardization

All API responses in this project follow a standardized format for consistency across all endpoints.

## Response Format

### Success Response

```json
{
  "terminus": "http://localhost:30010/api/v1/endpoint",
  "status": "OK",
  "response": {
    "code": 200,
    "title": "Operation successful",
    "message": "Operation successful",
    "data": {
      // Your actual data here
    }
  }
}
```

### Error Response

```json
{
  "terminus": "http://localhost:30010/api/v1/endpoint",
  "status": "F9",
  "response": {
    "title": "Operation failed",
    "message": "Error message here",
    "code": 400,
    "error_debug": "Detailed error message (development only)",
    "error_trace": "Stack trace (development only)"
  }
}
```

### Validation Error Response

```json
{
  "terminus": "http://localhost:30010/api/v1/endpoint",
  "status": "F9",
  "response": {
    "title": "Operation failed",
    "message": "Validation failed",
    "code": 422,
    "errors": {
      "email": ["email must be an email"],
      "password": ["password should not be empty"]
    }
  }
}
```

### Paginated Response

```json
{
  "terminus": "http://localhost:30010/api/v1/endpoint",
  "status": "OK",
  "response": {
    "code": 200,
    "title": "Operation successful",
    "message": "Data retrieved successfully",
    "pagination_meta": {
      "current_page": 1,
      "first_page_url": "http://localhost:30010/api/v1/endpoint?page=1",
      "from": 1,
      "last_page": 10,
      "last_page_url": "http://localhost:30010/api/v1/endpoint?page=10",
      "next_page_url": "http://localhost:30010/api/v1/endpoint?page=2",
      "path": "http://localhost:30010/api/v1/endpoint",
      "per_page": 10,
      "previous_page_url": null,
      "to": 10,
      "total": 100,
      "can_load_more": true
    },
    "data": [
      // Array of items
    ]
  }
}
```

## Usage

### Automatic Formatting (Default)

All controller methods automatically format responses. Just return your data:

```typescript
@Get('users')
async findAll() {
  const users = await this.usersService.findAll();
  return users; // Automatically formatted by ResponseInterceptor
}
```

### Custom Success Message

Inject `ApiHelper` and use it manually:

```typescript
import { ApiHelper } from '../../common/helpers/api.helper';

@Controller('users')
export class UsersController {
  constructor(
    private readonly usersService: UsersService,
    private readonly apiHelper: ApiHelper,
  ) {}

  @Get()
  async findAll(@Request() req) {
    const users = await this.usersService.findAll();
    return this.apiHelper.validResponse('Users retrieved successfully', users, req);
  }
}
```

### Paginated Responses

```typescript
@Get('users')
async findAll(@Request() req, @Query('page') page = 1, @Query('limit') limit = 10) {
  const [users, total] = await this.usersService.findAll(page, limit);
  return this.apiHelper.buildPaginatedResponse(users, total, page, limit, req);
}
```

### Error Handling

Errors are automatically formatted by `HttpExceptionFilter`:

```typescript
@Get(':id')
async findOne(@Param('id') id: string) {
  const user = await this.usersService.findOne(id);
  if (!user) {
    throw new NotFoundException('User not found');
    // Automatically formatted as error response
  }
  return user;
}
```

### Skip Formatting

Use `@SkipResponseFormat()` decorator to return raw responses:

```typescript
import { SkipResponseFormat } from '../../common/decorators/skip-response-format.decorator';

@Get('raw')
@SkipResponseFormat()
async getRaw() {
  return { custom: 'format' }; // Returns as-is
}
```

## API Constants

Use `ApiConstants` for consistent error codes:

```typescript
import ApiConstants from '../common/constants/api.constants';

// Available constants:
ApiConstants.GOOD_REQ_CODE          // 200
ApiConstants.BAD_REQ_ERR_CODE       // 400
ApiConstants.UNAUTHORIZED_ERR_CODE  // 401
ApiConstants.FORBIDDEN_ERR_CODE     // 403
ApiConstants.NOT_FOUND_ERR_CODE     // 404
ApiConstants.VALIDATION_ERR_CODE    // 422
ApiConstants.SERVER_ERR_CODE        // 500
```

## Files

- `src/common/helpers/api.helper.ts` - Main helper class
- `src/common/interceptors/response.interceptor.ts` - Global response interceptor
- `src/common/filters/http-exception.filter.ts` - Global exception filter
- `src/common/constants/api.constants.ts` - API response codes
- `src/common/decorators/skip-response-format.decorator.ts` - Skip formatting decorator
