npm package: @onlineapps/conn-orch-api-mapper
Description: API mapping connector for OA Drive - maps cookbook operations to HTTP endpoints
Author: OA Drive Team
Latest version: 1.0.30

# @onlineapps/conn-orch-api-mapper

## Overview
Maps cookbook operations to HTTP API endpoints. Bridges the gap between MQ-based workflow steps and RESTful service APIs.

## Installation
```bash
npm install @onlineapps/conn-orch-api-mapper
```

## Features
- Operation to endpoint mapping
- Parameter transformation
- Response mapping
- Header injection
- Service discovery integration
- OpenAPI schema support

## Usage

### Basic Setup
```javascript
const { ApiMapper } = require('@onlineapps/conn-orch-api-mapper');

const mapper = new ApiMapper({
  registryUrl: 'http://api_services_registry:33100',
  cacheEnabled: true,
  cacheTTL: 300
});

// Initialize mapper
await mapper.initialize();
```

### Operation Mapping
```javascript
// Map cookbook operation to HTTP request
const httpRequest = await mapper.mapOperation({
  service: 'hello-service',
  operation: 'greet',
  params: {
    name: 'World',
    language: 'en'
  }
});

// Returns:
{
  method: 'POST',
  url: 'http://hello-service:33199/api/greet',
  headers: {
    'Content-Type': 'application/json',
    'X-Workflow-Id': 'wf-uuid'
  },
  body: {
    name: 'World',
    language: 'en'
  }
}
```

### Response Mapping
```javascript
// Map HTTP response back to workflow format
const workflowResult = mapper.mapResponse({
  status: 200,
  headers: { 'content-type': 'application/json' },
  body: { greeting: 'Hello World' }
});

// Returns:
{
  success: true,
  data: { greeting: 'Hello World' },
  metadata: {
    httpStatus: 200,
    processingTime: 45
  }
}
```

## Configuration

### Options
```javascript
{
  registryUrl: 'http://registry:33100',  // Registry service URL
  cacheEnabled: true,                    // Cache service mappings
  cacheTTL: 300,                         // Cache TTL in seconds
  timeout: 5000,                         // HTTP request timeout
  retries: 3,                            // Retry attempts
  validateSchema: true                   // Validate against OpenAPI
}
```

### Environment Variables
```bash
REGISTRY_URL=http://api_services_registry:33100
API_MAPPER_CACHE_ENABLED=true
API_MAPPER_CACHE_TTL=300
API_MAPPER_TIMEOUT=5000
```

## Mapping Rules

### Default Mapping
```javascript
// Cookbook operation
{ service: 'service-name', operation: 'operation-name' }

// Maps to HTTP
POST /api/operation-name
```

### Custom Mappings
```javascript
// Define custom mappings
mapper.addMapping('hello-service', {
  greet: {
    method: 'POST',
    path: '/api/greet',
    paramMapping: {
      name: 'body.name',
      lang: 'query.language'
    }
  },
  status: {
    method: 'GET',
    path: '/health'
  }
});
```

## Service Discovery

The mapper integrates with the service registry:

```javascript
// Auto-discover service endpoints
const endpoint = await mapper.discoverEndpoint('hello-service');
// Returns: http://hello-service:33199

// Get service OpenAPI spec
const spec = await mapper.getServiceSpec('hello-service');
// Returns OpenAPI specification object
```

## Parameter Transformation

### Input Transformation
```javascript
// Transform cookbook params to HTTP request
const transformed = mapper.transformParams({
  params: { name: 'World', count: 5 },
  mapping: {
    name: 'body.name',
    count: 'query.limit'
  }
});

// Returns:
{
  body: { name: 'World' },
  query: { limit: 5 }
}
```

### Output Transformation
```javascript
// Transform HTTP response to workflow output
const output = mapper.transformResponse({
  response: { data: { items: [...] } },
  mapping: {
    'data.items': 'results',
    'data.total': 'count'
  }
});
```

## API Reference

### ApiMapper

#### initialize()
Initializes the mapper and loads service registry.

#### mapOperation(operation)
Maps a cookbook operation to HTTP request.

#### mapResponse(response)
Maps HTTP response to workflow result.

#### discoverEndpoint(serviceName)
Discovers service endpoint from registry.

#### getServiceSpec(serviceName)
Retrieves OpenAPI specification for service.

#### addMapping(serviceName, mappings)
Adds custom operation mappings.

#### transformParams(params, mapping)
Transforms parameters according to mapping rules.

## Integration with Service Wrapper

The API mapper is automatically used by service-wrapper:

```javascript
const { ServiceWrapper } = require('@onlineapps/service-wrapper');

const wrapper = new ServiceWrapper({
  apiMapping: {
    enabled: true,
    customMappings: {...}
  }
});

// API mapping is automatically configured
```

## OpenAPI Integration

Supports OpenAPI 3.0 specifications:

```javascript
// Validate against OpenAPI schema
const valid = await mapper.validateOperation({
  service: 'hello-service',
  operation: 'greet',
  params: { name: 'World' }
});

// Generate request from OpenAPI
const request = await mapper.fromOpenAPI({
  spec: openApiSpec,
  operationId: 'greetUser',
  params: { name: 'World' }
});
```

## Testing

```bash
npm test                 # Run all tests
npm run test:unit        # Unit tests only
npm run test:component   # Component tests
```

## Dependencies
- `@onlineapps/conn-orch-registry` - Service registry client
- `axios` - HTTP client
- `openapi-validator` - Schema validation

## Error Propagation

When a downstream service returns an HTTP error, `_callViaHttp` preserves the full response body instead of discarding it. The thrown error carries:

- `statusCode` -- HTTP status code (enables `ErrorClassifier` classification)
- `errorCode` -- machine-readable code from the response (e.g. `RESOURCE_NOT_FOUND`)
- `type` -- error type from the response (e.g. `BUSINESS`, `VALIDATION`)
- `details` -- array of detail strings from the response
- `service` / `operation` -- originating service and operation
- `responseBody` -- raw response data for debugging

This enables the WorkflowOrchestrator to classify errors accurately and skip retries for permanent failures (BUSINESS/VALIDATION). See [Error Handling Standard](/docs/standards/ERROR_HANDLING.md#business-service-error-standard).

## Related Documentation
- [Service Wrapper](/shared/connector/service-wrapper/README.md) - Integration guide
- [Registry System](/docs/modules/registry.md) - Service discovery
- [Cookbook Connector](/shared/connector/conn-orch-cookbook/README.md) - Operation format
- [Error Handling Standard](/docs/standards/ERROR_HANDLING.md) - Business error classes and response format

---
*Version: 1.0.31 | License: MIT*