Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 | 2x 57x 2x 55x 55x 55x 55x 55x 55x 2x 2x 2x 3x 3x 2x 1x 7x 7x 11x 11x 8x 4x 4x 3x 3x 1x 1x 3x 1x 6x 2x 6x 14x 11x 3x 12x 12x 1x 11x 11x 11x 11x 2x 9x 8x 3x 3x 60x 60x 1x 59x 138x 272x 272x 272x 59x 59x 20x 20x 20x 29x 7x 7x 22x 4x 18x 20x 7x 7x 7x 14x 12x 2x 5x 15x 15x 20x 20x 9x 11x 10x 1x 1x 15x 3x 3x 15x 9x 9x 6x 3x 1x 2x 2x 2x | 'use strict';
const axios = require('axios');
/**
* @class ApiMapper
* @description Maps cookbook operations to HTTP API endpoints using OpenAPI specification.
* Handles request building, variable resolution, and response transformation.
*
* This is the core logic moved from service-wrapper's ApiCaller to make
* service-wrapper a true thin orchestration layer.
*/
class ApiMapper {
/**
* Create a new ApiMapper instance
* @constructor
* @param {Object} config - Configuration object
* @param {Object|string} config.openApiSpec - OpenAPI specification object or path
* @param {string} [config.serviceUrl='http://localhost:3000'] - Base URL of the service
* @param {Object} [config.service] - Express app instance for direct calls
* @param {boolean} [config.directCall=false] - Use direct Express calls instead of HTTP
* @param {Object} [config.logger] - Logger instance
* @param {number} [config.port=3000] - Service port for direct calls
*
* @example
* const apiMapper = new ApiMapper({
* openApiSpec: require('./openapi.json'),
* serviceUrl: 'http://hello-service:3000'
* });
*/
constructor(config) {
if (!config.openApiSpec) {
throw new Error('OpenAPI specification is required');
}
this.openApiSpec = config.openApiSpec;
this.serviceUrl = config.serviceUrl || `http://localhost:${config.port || 3000}`;
this.service = config.service; // Express app for direct calls
this.directCall = config.directCall === true;
this.logger = config.logger || console;
// Parse OpenAPI to create operation map
this.operations = this._parseOpenApiSpec(this.openApiSpec);
}
/**
* Load OpenAPI specification
* @method loadOpenApiSpec
* @param {Object|string} spec - OpenAPI specification or path
* @returns {Object} Parsed operations map
*/
loadOpenApiSpec(spec) {
this.openApiSpec = spec;
this.operations = this._parseOpenApiSpec(spec);
return this.operations;
}
/**
* Map operation name to HTTP endpoint details
* @method mapOperationToEndpoint
* @param {string} operationName - Operation ID from cookbook
* @returns {Object} Endpoint details {method, path, parameters}
*
* @example
* const endpoint = apiMapper.mapOperationToEndpoint('getUser');
* // Returns: {method: 'GET', path: '/users/{id}', parameters: [...]}
*/
mapOperationToEndpoint(operationName) {
const operation = this.operations[operationName];
if (!operation) {
throw new Error(`Operation not found: ${operationName}`);
}
return operation;
}
/**
* Transform cookbook parameters to HTTP request
* @method transformRequest
* @param {Object} cookbookParams - Parameters from cookbook step
* @param {Object} openApiParams - OpenAPI parameter definitions
* @returns {Object} Transformed request {params, query, body, headers}
*
* @example
* const request = apiMapper.transformRequest(
* {userId: '123', name: 'John'},
* operation.parameters
* );
*/
transformRequest(cookbookParams, openApiParams) {
const result = {
params: {},
query: {},
body: null,
headers: {}
};
// Process each parameter according to OpenAPI spec
openApiParams.forEach(param => {
const value = cookbookParams[param.name];
if (value !== undefined) {
switch (param.in) {
case 'path':
result.params[param.name] = value;
break;
case 'query':
result.query[param.name] = value;
break;
case 'header':
result.headers[param.name] = value;
break;
}
} else if (param.required) {
throw new Error(`Required parameter missing: ${param.name}`);
}
});
// Handle request body
if (cookbookParams.body) {
result.body = cookbookParams.body;
}
return result;
}
/**
* Transform HTTP response to cookbook format
* @method transformResponse
* @param {Object} httpResponse - HTTP response
* @returns {Object} Transformed response for cookbook
*/
transformResponse(httpResponse) {
// Extract relevant data from HTTP response
if (httpResponse.data) {
return httpResponse.data;
}
return httpResponse;
}
/**
* Call operation with parameters
* @async
* @method callOperation
* @param {string} operationId - Operation identifier
* @param {Object} input - Input data for the operation
* @param {Object} context - Workflow context
* @returns {Promise<Object>} API response
*
* @example
* const result = await apiMapper.callOperation('getUser', {id: '123'}, context);
*/
async callOperation(operationId, input = {}, context = {}) {
const operation = this.operations[operationId];
if (!operation) {
throw new Error(`Operation not found: ${operationId}`);
}
try {
// Resolve variables in input using context
const resolvedInput = this._resolveVariables(input, context);
// Build request
const request = this._buildRequest(operation, resolvedInput);
// Make the call
let response;
if (this.service && this.directCall) {
response = await this._callDirectly(request);
} else {
response = await this._callViaHttp(request);
}
// Transform and return response
return this.transformResponse(response);
} catch (error) {
this.logger.error(`API call failed for ${operationId}`, {
error: error.message,
input,
operation
});
throw error;
}
}
/**
* Parse OpenAPI specification to extract operations
* @private
* @param {Object} spec - OpenAPI specification
* @returns {Object} Operations map
*/
_parseOpenApiSpec(spec) {
const operations = {};
if (!spec || !spec.paths) {
return operations;
}
// Extract all operations from OpenAPI paths
Object.entries(spec.paths).forEach(([path, pathItem]) => {
Object.entries(pathItem).forEach(([method, operation]) => {
Eif (['get', 'post', 'put', 'patch', 'delete'].includes(method)) {
const operationId = operation.operationId ||
`${method}_${path.replace(/[^a-zA-Z0-9]/g, '_')}`;
operations[operationId] = {
method: method.toUpperCase(),
path,
parameters: operation.parameters || [],
requestBody: operation.requestBody,
responses: operation.responses,
summary: operation.summary,
description: operation.description
};
}
});
});
this.logger.info(`Parsed ${Object.keys(operations).length} operations from OpenAPI spec`);
return operations;
}
/**
* Resolve variables in input using context
* @private
* @param {Object} input - Input with potential variable references
* @param {Object} context - Context containing variable values
* @returns {Object} Resolved input
*/
_resolveVariables(input, context) {
Iif (!input || typeof input !== 'object') {
return input;
}
const resolved = {};
Object.entries(input).forEach(([key, value]) => {
if (typeof value === 'string' && value.startsWith('${') && value.endsWith('}')) {
// Variable reference: ${context.path.to.value}
const path = value.slice(2, -1);
resolved[key] = this._getValueFromPath(context, path);
} else if (typeof value === 'object' && value !== null) {
// Recursive resolution
resolved[key] = this._resolveVariables(value, context);
} else {
resolved[key] = value;
}
});
return resolved;
}
/**
* Get value from object using dot notation path
* @private
* @param {Object} obj - Object to search
* @param {string} path - Dot notation path
* @returns {*} Value at path
*/
_getValueFromPath(obj, path) {
const parts = path.split('.');
let current = obj;
for (const part of parts) {
if (current && typeof current === 'object' && part in current) {
current = current[part];
} else {
return undefined;
}
}
return current;
}
/**
* Build HTTP request from operation and input
* @private
* @param {Object} operation - Operation definition
* @param {Object} input - Resolved input
* @returns {Object} Request object
*/
_buildRequest(operation, input) {
const request = {
method: operation.method,
url: this.serviceUrl + operation.path,
params: {},
headers: {},
data: null
};
// Process path parameters
operation.parameters.forEach(param => {
const value = input[param.name];
if (param.in === 'path') {
// Replace path parameter in URL
request.url = request.url.replace(`{${param.name}}`, value);
} else if (param.in === 'query') {
request.params[param.name] = value;
} else Eif (param.in === 'header') {
request.headers[param.name] = value;
}
});
// Add request body if present
if (operation.requestBody && input.body) {
request.data = input.body;
request.headers['Content-Type'] = 'application/json';
}
return request;
}
/**
* Call service directly via Express app
* @private
* @async
* @param {Object} request - Request object
* @returns {Promise<Object>} Response
*/
async _callDirectly(request) {
// Create mock req/res objects for Express
const mockReq = {
method: request.method,
url: request.url.replace(this.serviceUrl, ''),
params: {},
query: request.params,
body: request.data,
headers: request.headers
};
// Extract path params from URL
const pathMatch = mockReq.url.match(/\/[^?]*/);
if (pathMatch) {
mockReq.path = pathMatch[0];
}
return new Promise((resolve, reject) => {
const mockRes = {
status: function(code) {
this.statusCode = code;
return this;
},
json: function(data) {
resolve({ data, status: this.statusCode || 200 });
},
send: function(data) {
resolve({ data, status: this.statusCode || 200 });
}
};
// Call Express app directly
this.service(mockReq, mockRes, (err) => {
if (err) reject(err);
else reject(new Error('Route not found'));
});
});
}
/**
* Call service via HTTP
* @private
* @async
* @param {Object} request - Request object
* @returns {Promise<Object>} Response
*/
async _callViaHttp(request) {
try {
const response = await axios(request);
return response;
} catch (error) {
if (error.response) {
// Server responded with error
throw new Error(`API returned ${error.response.status}: ${error.response.statusText}`);
} else Iif (error.request) {
// Request made but no response
throw new Error(`No response from service: ${request.url}`);
} else {
throw error;
}
}
}
}
module.exports = ApiMapper; |