npm package: @simplicate/api-message
Description: A TypeScript library for handling API messages
Latest version: 1.0.0

# @simplicate/api-message

A TypeScript library for handling standardized API messages and responses.

## Installation

```bash
npm install @simplicate/api-message
```

## Features

- 🎯 **Standardized API Responses**: Consistent success and error response structures
- 🚀 **HTTP Status Helpers**: Convenient functions for common HTTP status responses
- 🔍 **Zod Validation**: Built-in schemas for runtime validation
- 📝 **TypeScript First**: Full type safety with TypeScript support
- ✅ **Well Tested**: Comprehensive test coverage
- 📊 **Additional Types**: Request structures and pagination support

## Usage

### API Responses

```typescript
import { apiSuccess, apiError, ApiResponse } from '@simplicate/api-message';

// Create success responses
const successResponse = apiSuccess({ id: 1, name: 'John' }, 'User created successfully');
// {
//   status: 'success',
//   message: 'User created successfully',
//   data: { id: 1, name: 'John' },
//   timestamp: '2025-08-11T13:52:30.123Z'
// }

// Create error responses
const errorResponse = apiError('User not found', 'NOT_FOUND', { userId: 123 });
// {
//   status: 'error',
//   code: 'NOT_FOUND',
//   message: 'User not found',
//   details: { userId: 123 },
//   timestamp: '2025-08-11T13:52:30.123Z'
// }

// With metadata
const responseWithMeta = apiSuccess(
  { items: [] },
  'Success',
  { requestId: 'req-123', source: 'api-v1' }
);
```

### HTTP Status Helpers

```typescript
import {
  apiCreated,
  apiNotFound,
  apiValidationError,
  apiUnauthorized,
  apiForbidden,
  apiConflict,
  apiInternalError
} from '@simplicate/api-message';

// HTTP 201 - Created
const created = apiCreated({ id: 123, name: 'John' }, 'User created');

// HTTP 404 - Not Found
const notFound = apiNotFound('User not found', { userId: 123 });

// HTTP 400 - Bad Request/Validation Error
const validationError = apiValidationError('Invalid email', { field: 'email' });

// HTTP 401 - Unauthorized
const unauthorized = apiUnauthorized('Invalid credentials');

// HTTP 403 - Forbidden
const forbidden = apiForbidden('Access denied');

// HTTP 409 - Conflict
const conflict = apiConflict('Email already exists', { email: 'user@example.com' });

// HTTP 500 - Internal Server Error
const serverError = apiInternalError('Database connection failed');
```

### Validation with Zod

```typescript
import { 
  apiSuccessResponseSchema,
  apiErrorResponseSchema,
  apiErrorCodes
} from '@simplicate/api-message';

// Validate responses
const response = { /* ... */ };
const validatedSuccess = apiSuccessResponseSchema.parse(response);
const validatedError = apiErrorResponseSchema.parse(response);

// Use error codes enum
const validCodes = apiErrorCodes.options;
// ['ERROR', 'NOT_FOUND', 'VALIDATION_ERROR', ...]
```

### Additional Types

```typescript
import {
  ApiRequest,
  PaginationMeta,
  PaginatedData
} from '@simplicate/api-message';

// API Request structure
const request: ApiRequest<{ name: string }> = {
  data: { name: 'John' },
  headers: { 'Content-Type': 'application/json' },
  meta: { requestId: 'req-123' },
  timestamp: new Date().toISOString()
};

// Pagination metadata
const pagination: PaginationMeta = {
  page: 1,
  limit: 10,
  total: 100,
  totalPages: 10,
  hasNext: true,
  hasPrevious: false
};

// Paginated response
const paginatedResponse = apiSuccess<PaginatedData<{ id: number; name: string }>>({
  items: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }],
  pagination
}, 'Users retrieved successfully');
```

## API Reference

### Types

#### `ApiSuccessResponse<TData>`
Standard success response structure.

#### `ApiErrorResponse`
Standard error response structure.

#### `ApiResponse<TData>`
Union type of success and error responses.

#### `ApiErrorCode`
Standardized error codes:
- `ERROR` - Generic error
- `NOT_FOUND` - Resource not found
- `VALIDATION_ERROR` - Input validation failed
- `UNAUTHORIZED` - Authentication required
- `FORBIDDEN` - Access denied
- `CONFLICT` - Resource conflict
- `BAD_REQUEST` - Invalid request
- `INTERNAL_SERVER_ERROR` - Server error

#### `ApiRequest<TData>`
Generic API request structure with optional data, headers, metadata and timestamp.

#### `PaginationMeta`
Pagination metadata structure with page, limit, total, totalPages, hasNext, hasPrevious.

#### `PaginatedData<TItem>`
Paginated response data structure containing items array and pagination metadata.

### Functions

#### Core Functions

#### `apiSuccess<TData>(data: TData, message?: string, meta?: Record<string, any>)`
Creates a standardized success response.

#### `apiError(message: string, code?: ApiErrorCode, details?: unknown, meta?: Record<string, any>)`
Creates a standardized error response.

#### HTTP Status Helpers

- `apiCreated<TData>(data: TData, message?, meta?)` - HTTP 201 Created response
- `apiNotFound(message?, details?, meta?)` - HTTP 404 Not Found response
- `apiValidationError(message?, details?, meta?)` - HTTP 400 Bad Request/Validation response
- `apiUnauthorized(message?, details?, meta?)` - HTTP 401 Unauthorized response
- `apiForbidden(message?, details?, meta?)` - HTTP 403 Forbidden response
- `apiConflict(message?, details?, meta?)` - HTTP 409 Conflict response
- `apiInternalError(message?, details?, meta?)` - HTTP 500 Internal Server Error response

## Development

```bash
# Install dependencies
npm install

# Build the library
npm run build

# Run tests
npm test

# Watch mode for development
npm run build:watch
npm run test:watch

# Lint code
npm run lint
```

## Publishing

```bash
# Build and publish
npm run build
npm publish
```

## License

MIT