CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-swagger-client

SwaggerJS - a collection of interfaces for OAI specs

Pending
Overview
Eval results
Files

helpers.mddocs/

Helper Utilities and Spec Analysis

Utility functions for working with OpenAPI specifications, operations, and generating identifiers.

Capabilities

Spec Analysis Utilities

Utilities for analyzing and working with OpenAPI specifications.

/**
 * Iterate over all operations in a specification
 * @param spec - OpenAPI specification object
 * @param callback - Function called for each operation
 * @param find - If true, stops iterating when callback returns truthy value
 * @returns Operation object if find=true and match found, undefined otherwise
 */
function eachOperation(spec: object, callback: OperationCallback, find?: boolean): OperationInfo | undefined;

interface OperationCallback {
  (operationInfo: OperationInfo): any;
}

interface OperationInfo {
  /** Path name (e.g., "/users/{id}") */
  pathName: string;
  /** HTTP method (e.g., "get", "post") */
  method: string;
  /** Operation object from spec */
  operation: OperationObject;
}

/**
 * Find operation matching a predicate function
 * @param spec - OpenAPI specification object
 * @param predicate - Function to test each operation
 * @returns First matching operation or undefined
 */
function findOperation(spec: object, predicate: OperationPredicate): OperationInfo | undefined;

interface OperationPredicate {
  (operationInfo: OperationInfo): boolean;
}

/**
 * Get raw operation object by operation ID
 * @param spec - OpenAPI specification object
 * @param operationId - Operation ID to find
 * @returns Raw operation info or undefined
 */
function getOperationRaw(spec: object, operationId: string): OperationInfo | undefined;

Usage Examples:

import { eachOperation, findOperation, getOperationRaw } from "swagger-client";

// Iterate over all operations
eachOperation(openApiSpec, ({ pathName, method, operation }) => {
  console.log(`${method.toUpperCase()} ${pathName}: ${operation.operationId}`);
});

// Find operation by criteria
const operation = findOperation(openApiSpec, ({ operation }) => {
  return operation.tags && operation.tags.includes("users");
});

// Get specific operation
const operation = getOperationRaw(openApiSpec, "getUserById");
if (operation) {
  console.log(`Found operation: ${operation.method} ${operation.pathName}`);
}

// Count operations by tag
const tagCounts = {};
eachOperation(openApiSpec, ({ operation }) => {
  const tags = operation.tags || ["untagged"];
  tags.forEach(tag => {
    tagCounts[tag] = (tagCounts[tag] || 0) + 1;
  });
});

Operation ID Generation

Generate operation IDs from operations and paths.

/**
 * Generate operation ID from operation details
 * @param operation - Operation object
 * @param pathName - Path name
 * @param method - HTTP method
 * @param options - Generation options
 * @returns Generated operation ID
 */
function opId(
  operation: OperationObject, 
  pathName: string, 
  method: string, 
  options?: OpIdOptions
): string;

interface OpIdOptions {
  /** Use v2 compatibility mode */
  v2OperationIdCompatibilityMode?: boolean;
}

/**
 * Generate operation ID from path and method (current algorithm)
 * @param pathName - Path name
 * @param method - HTTP method
 * @returns Generated operation ID
 */
function idFromPathMethod(pathName: string, method: string): string;

/**
 * Generate operation ID from path and method (legacy algorithm) 
 * @param pathName - Path name
 * @param method - HTTP method
 * @returns Generated operation ID
 */
function idFromPathMethodLegacy(pathName: string, method: string): string;

Usage Examples:

import { opId, idFromPathMethod, idFromPathMethodLegacy } from "swagger-client";

// Generate ID from operation (prefers existing operationId)
const operation = {
  operationId: "createUser",
  summary: "Create a new user"
};
const id = opId(operation, "/users", "post");
console.log(id); // "createUser"

// Generate ID when no operationId exists
const operation = {
  summary: "Get user by ID"
};
const id = opId(operation, "/users/{id}", "get");
console.log(id); // "getUsersById" (generated)

// Generate ID from path and method
const id = idFromPathMethod("/users/{id}/posts", "get");
console.log(id); // "getUsersIdPosts"

// Legacy ID generation (for backward compatibility)
const id = idFromPathMethodLegacy("/api/v1/users/{userId}", "post");
console.log(id); // "postApiV1UsersUserId"

// V2 compatibility mode
const id = opId(operation, "/users/{id}", "get", {
  v2OperationIdCompatibilityMode: true
});

URL Validation

Validate and check URL formats.

/**
 * Check if string is a valid HTTP/HTTPS URL
 * @param url - String to validate
 * @returns Whether string is valid HTTP URL
 */
function isHttpUrl(url: string): boolean;

Usage Examples:

import { isHttpUrl } from "swagger-client";

// Validate URLs
console.log(isHttpUrl("https://api.example.com")); // true
console.log(isHttpUrl("http://localhost:3000")); // true
console.log(isHttpUrl("ftp://files.example.com")); // false
console.log(isHttpUrl("not-a-url")); // false
console.log(isHttpUrl("//example.com")); // false

// Use in validation
function validateSpecUrl(spec) {
  if (spec.host && !isHttpUrl(`https://${spec.host}`)) {
    throw new Error("Invalid host in specification");
  }
  
  if (spec.servers) {
    spec.servers.forEach(server => {
      if (!isHttpUrl(server.url) && !server.url.startsWith("/")) {
        throw new Error(`Invalid server URL: ${server.url}`);
      }
    });
  }
}

String Processing Utilities

Utilities for processing and normalizing strings.

/**
 * Replace special characters with underscores
 * @param str - String to process
 * @returns Processed string with underscores
 */
function replaceSpecialCharsWithUnderscore(str: string): string;

Usage Examples:

import { replaceSpecialCharsWithUnderscore } from "swagger-client";

// String normalization for IDs
const operationId = replaceSpecialCharsWithUnderscore("get-user-by-id");
console.log(operationId); // "get_user_by_id"

const tagName = replaceSpecialCharsWithUnderscore("User Management");
console.log(tagName); // "User_Management"

// Use in ID generation
function normalizeOperationId(pathName, method) {
  const rawId = `${method}${pathName}`;
  return replaceSpecialCharsWithUnderscore(rawId);
}

Interface Generation Utilities

Utilities for creating tag-based operation interfaces.

/**
 * Create bound execute function for operations
 * @param swaggerClient - SwaggerClient instance
 * @returns Execute function bound to client
 */
function makeExecute(swaggerClient: SwaggerClientInstance): ExecuteFunction;

interface ExecuteFunction {
  (operationInfo: OperationExecuteInfo): ParameterizedExecuteFunction;
}

interface OperationExecuteInfo {
  pathName: string;
  method: string;
  operationId: string;
}

interface ParameterizedExecuteFunction {
  (parameters?: ParameterValues, options?: ExecutionOptions): Promise<ResponseObject>;
}

/**
 * Map operations to tags for organization
 * @param options - Mapping options
 * @returns Tag-based operation mapping
 */
function mapTagOperations(options: MapTagOperationsOptions): TaggedOperations;

interface MapTagOperationsOptions {
  spec: object;
  cb?: OperationCallback;
  defaultTag?: string;
  v2OperationIdCompatibilityMode?: boolean;
}

interface TaggedOperations {
  [tagName: string]: {
    [operationId: string]: ParameterizedExecuteFunction;
  };
}

Usage Examples:

// Create tag-based interfaces
const tagOperations = mapTagOperations({
  spec: openApiSpec,
  cb: makeExecute(swaggerClient),
  defaultTag: "default"
});

// Use generated interfaces
const userOps = tagOperations.users;
const response = await userOps.getUserById({ userId: "123" });

// Custom operation callback
const tagOperations = mapTagOperations({
  spec: openApiSpec,
  cb: ({ operationId, pathName, method }) => {
    return async (params) => {
      console.log(`Executing ${operationId}: ${method} ${pathName}`);
      return execute({
        spec: openApiSpec,
        operationId,
        parameters: params
      });
    };
  }
});

Common Types

interface OperationObject {
  operationId?: string;
  tags?: string[];
  summary?: string;
  description?: string;
  parameters?: ParameterObject[];
  requestBody?: RequestBodyObject;
  responses?: ResponsesObject;
  security?: SecurityRequirement[];
}

interface OperationInfo {
  pathName: string;
  method: string;
  operation: OperationObject;
}

interface OperationCallback {
  (operationInfo: OperationInfo): any;
}

interface OperationPredicate {
  (operationInfo: OperationInfo): boolean;
}

interface SwaggerClientInstance {
  spec: object;
  execute(options: ExecutionOptions): Promise<ResponseObject>;
}

interface ParameterValues {
  [parameterName: string]: any;
}

interface ExecutionOptions {
  operationId?: string;
  pathName?: string;
  method?: string;
  parameters?: ParameterValues;
}

interface ResponseObject {
  status: number;
  statusText: string;
  headers: Record<string, string>;
  body: any;
  text: string;
  ok: boolean;
}

Install with Tessl CLI

npx tessl i tessl/npm-swagger-client

docs

client-construction.md

execution.md

helpers.md

http-client.md

index.md

request-building.md

resolution.md

tile.json