# API Generator Guide

## Overview

The API generator provides automated generation of RESTful API endpoints for your models. It supports two types of API generation:

1. **CRUD APIs**: Standard RESTful operations (Create, Read, Update, Delete) for individual records
2. **Bulk APIs**: Operations for handling multiple records at once

## Generated Endpoints

### CRUD APIs (`pnpm gen-api`)

Generates the following endpoints:

- `GET /{apiPath}` - Get all records (with pagination, filtering, sorting)
- `POST /{apiPath}` - Create a single record
- `GET /{apiPath}/{id}` - Get a record by ID
- `PUT /{apiPath}/{id}` - Update a record by ID
- `DELETE /{apiPath}/{id}` - Delete a record by ID

### Bulk APIs (`pnpm gen-api-bulk`)

Generates the following endpoints:

- `POST /{apiPath}` - Create multiple records (bulk create)
- `PUT /{apiPath}` - Update multiple records (bulk update)
- `DELETE /{apiPath}` - Delete multiple records (bulk delete)

## Usage

### Generate CRUD APIs

```bash
pnpm gen-api <model> [domain] [apiPath] [swaggerTag]
```

**Parameters:**

- `model` (required): Model name (must exist in your models)
- `domain` (optional): Domain folder (e.g., user-management)
- `apiPath` (optional): API path (defaults to model name)
- `swaggerTag` (optional): Swagger tag (defaults to capitalized model name)

**Examples:**

```bash
# Basic usage
pnpm gen-api user

# With domain
pnpm gen-api user user-management

# Full parameters
pnpm gen-api user user-management users UserManagement
```

### Generate Bulk APIs

```bash
pnpm gen-api-bulk <model> [domain] [apiPath] [swaggerTag]
```

**Parameters:**

- `model` (required): Model name (must exist in your models)
- `domain` (optional): Domain folder (e.g., user-management)
- `apiPath` (optional): API path (defaults to model name)
- `swaggerTag` (optional): Swagger tag (defaults to capitalized model name)

**Examples:**

```bash
# Basic usage
pnpm gen-api-bulk user

# With domain
pnpm gen-api-bulk user user-management

# Full parameters
pnpm gen-api-bulk user user-management users UserManagement
```

## Response Format

All generated endpoints use the standardized response format:

### Success Response

```json
{
	"message": null,
	"message_en": null,
	"responseData": {
		"id": "123",
		"name": "Example"
	},
	"status": "success",
	"timeStamp": "2025-12-08 10:00:00",
	"violations": null
}
```

### Error Response

```json
{
  "message": "Dữ liệu đầu vào không hợp lệ",
  "message_en": "Invalid input data",
  "responseData": null,
  "status": "error",
  "timeStamp": "2025-12-08 10:00:00",
  "violations": {
    "type": "VALIDATION_ERROR",
    "code": 400,
    "additionalData": {
      "errors": [...]
    }
  }
}
```

## File Structure

After generation, the following files are created:

```
src/controllers/api/v1.0/{domain}/{apiPath}/
├── index.ts          # Main endpoints (GET all + POST for CRUD, bulk operations for bulk)
└── {id}.ts           # ID-based endpoints (only for CRUD)

src/providers/{domain}/
└── {ModelName}Provider.ts  # Data access layer
```

## Authentication

- GET endpoints: Require authentication (Bearer token)
- POST/PUT/DELETE endpoints: Require authentication + authorization

## Middleware

- `queryModifier`: Handles pagination, filtering, sorting for GET requests
- `verify`: JWT authentication middleware
- `validator`: Input validation (if configured)

## Swagger Documentation

All endpoints are automatically documented with OpenAPI/Swagger specifications including:

- Request/response schemas
- Authentication requirements
- Parameter definitions
- Error responses

## Best Practices

1. **Use CRUD for single operations**: When you need to manipulate individual records
2. **Use Bulk for batch operations**: When importing data, updating multiple records, or bulk deletions
3. **Domain organization**: Use domains to group related APIs (e.g., `user-management`, `product-catalog`)
4. **Consistent naming**: Keep API paths consistent with model names
5. **Test generated code**: Always test the generated endpoints before deploying

## Customization

The templates are located in `lib/generator/api/templates/`:

- `controllerAllPath.mustache` - All records endpoints (GET all + POST for CRUD, bulk operations for bulk)
- `controllerIdPath.mustache` - ID-based CRUD operations
- `provider.mustache` - Data provider template

Modify these templates to customize the generated code according to your needs.
