Skip to content

api-generator 0.3.1

Install from the command line:
Learn more about npm packages
$ npm install @generation-one/api-generator@0.3.1
Install via package.json:
"@generation-one/api-generator": "0.3.1"

About this version

G1 API Generator

A command-line tool for generating TypeScript API clients from OpenAPI schemas.

Features

  • Downloads OpenAPI schema from a specified URL
  • Generates TypeScript interfaces and API client code
  • Post-processes generated code to fix common issues
  • Supports HTTPS with option to skip TLS verification
  • Detects and warns about duplicate DTOs in the schema

Installation

# Install from G1 package registry
npm install @g1/api-generator --save-dev

# Or with pnpm
pnpm add @g1/api-generator -D

Usage

Command Line

# Basic usage
g1-api-generator https://your-api-server/openapi/schema.json ./src/lib/api

# Skip TLS verification (useful for local development with self-signed certificates)
g1-api-generator https://localhost:7205/openapi/schema.json ./src/lib/api --skip-tls-verify

# Generate with custom client name for multiple endpoint support
g1-api-generator https://your-api-server/openapi/schema.json ./src/lib/api --client-name MyApiClient

In package.json scripts

{
  "scripts": {
    "api:generate": "g1-api-generator https://localhost:7205/openapi/schema.json src/lib/api"
  }
}

Programmatic Usage

import { generateApiClient } from '@g1/api-generator';

async function generateApi() {
  await generateApiClient({
    schemaUrl: 'https://your-api-server/openapi/schema.json',
    outputDir: './src/lib/api',
    skipTlsVerify: true, // Optional, default: false
    runPostProcessing: true, // Optional, default: true
    clientName: 'MyApiClient' // Optional, enables factory pattern for multiple endpoints
  });
}

generateApi().catch(console.error);

Generated Code Structure

The generated code is organized as follows:

  • models/ - TypeScript interfaces for API models
  • services/ - API client services for making requests
  • core/ - Core functionality for the API client
  • ClientFactory.ts - Factory class for creating multiple client instances (when clientName is provided)
  • open-api.json - The downloaded and processed OpenAPI schema

Examples

The package includes comprehensive examples demonstrating various usage patterns:

Example Files

  • examples/factory-pattern-usage.ts - Complete examples showing:
    • Basic factory pattern usage with multiple endpoints
    • Multi-tenant applications with different API endpoints
    • Configuration-driven client creation
    • Custom security systems (public key signatures, JWT, OAuth, API keys)
    • Request/response interceptors
    • Backward compatibility patterns
    • Advanced client management

Running Examples

# View the example file
cat examples/factory-pattern-usage.ts

# Run examples (after generating a client)
npx ts-node examples/factory-pattern-usage.ts

Multiple Endpoint Support (Factory Pattern)

When you specify a clientName, the generator creates a factory pattern that allows you to create multiple client instances with different endpoint configurations:

Basic Factory Usage

import { ClientFactory } from './src/lib/api/ClientFactory';

// Create multiple clients for different endpoints
const client1 = ClientFactory.create({
  endpoint: 'https://api1.example.com'
});

const client2 = ClientFactory.create({
  endpoint: 'https://api2.example.com',
  token: 'your-auth-token'
});

// Both clients can be used simultaneously
const response1 = await client1.users.getUsers();
const response2 = await client2.orders.getOrders();

Advanced Factory Configuration

import { ClientFactory } from './src/lib/api/ClientFactory';

const client = ClientFactory.create({
  endpoint: 'https://api.example.com',
  token: 'your-auth-token',
  headers: {
    'X-Custom-Header': 'custom-value'
  },
  timeout: 10000 // 10 seconds
});

Custom Security Systems

The factory pattern supports different authentication and security systems through request interception:

Public Key Signature Authentication

import { ClientFactory } from './src/lib/api/ClientFactory';

const client = ClientFactory.create({
  endpoint: 'https://secure-api.com'
});

// Override the request method to add custom signature
const originalRequest = client.request;
client.request = async (options: any) => {
  const timestamp = Date.now().toString();
  const requestData = JSON.stringify({
    method: options.method,
    url: options.url,
    body: options.body,
    timestamp
  });

  // Generate signature (replace with actual crypto implementation)
  const signature = await generatePublicKeySignature(requestData, 'your-private-key');

  // Add signature headers
  options.headers = {
    ...options.headers,
    'X-Timestamp': timestamp,
    'X-Signature': signature,
    'X-Public-Key-ID': 'your-public-key-id'
  };

  return originalRequest.call(client, options);
};

// All requests now include the signature
const data = await client.users.getUsers();

Multiple Security Systems

// OAuth2 API
const oauthClient = ClientFactory.create({
  endpoint: 'https://oauth-api.com',
  token: 'bearer-token'
});

// API Key API
const apiKeyClient = ClientFactory.create({
  endpoint: 'https://apikey-api.com',
  headers: {
    'X-API-Key': 'your-api-key'
  }
});

// Custom JWT API with request interception
const jwtClient = ClientFactory.create({
  endpoint: 'https://jwt-api.com'
});

jwtClient.request = async (options: any) => {
  const token = await generateJWT({
    issuer: 'your-app',
    audience: 'jwt-api.com',
    privateKey: 'your-jwt-private-key'
  });

  options.headers = {
    ...options.headers,
    'Authorization': `Bearer ${token}`
  };

  return originalRequest.call(jwtClient, options);
};

// Use all clients simultaneously with their respective security systems
const [oauthData, apiKeyData, jwtData] = await Promise.all([
  oauthClient.users.getUsers(),
  apiKeyClient.products.getProducts(),
  jwtClient.analytics.getAnalytics()
]);

Backward Compatibility

For existing code, you can still use the legacy approach:

import { MyApiClient, createClient } from './src/lib/api';

// Legacy approach (still works)
const api = new MyApiClient({
  BASE: 'https://api.example.com',
  TOKEN: 'your-token'
});

// Or using the legacy helper function
const api2 = createClient({
  BASE: 'https://api.example.com',
  TOKEN: 'your-token'
});

Migration Guide

From v0.2.x to v0.3.0

Version 0.3.0 introduces factory pattern support for multiple endpoint configurations. Here's how to migrate:

Option 1: Use the New Factory Pattern (Recommended)

  1. Regenerate your API client with a client name:

    g1-api-generator https://your-api-server/openapi/schema.json ./src/lib/api --client-name ApiClient
  2. Update your code to use the factory:

    // Before (v0.2.x)
    import { ApiClient } from './src/lib/api';
    const api = new ApiClient({ BASE: 'https://api.example.com', TOKEN: 'token' });
    
    // After (v0.3.0) - Recommended
    import { ClientFactory } from './src/lib/api/ClientFactory';
    const api = ClientFactory.create({ endpoint: 'https://api.example.com', token: 'token' });
  3. Benefits of the factory pattern:

    • Support for multiple client instances with different endpoints
    • Cleaner configuration interface
    • Better TypeScript support
    • Future-proof architecture

Option 2: Keep Existing Code (Backward Compatible)

Your existing code will continue to work without changes. The legacy approach is still supported:

import { ApiClient } from './src/lib/api';
const api = new ApiClient({ BASE: 'https://api.example.com', TOKEN: 'token' });

Post-Processing

The tool automatically applies the following post-processing to the generated code:

  1. Removes import statements for void type
  2. Replaces usages of void as a type with any
  3. Detects and replaces self-referencing DTOs with any
  4. Adds auto-generated comments to files
  5. Generates factory class when clientName is provided

License

UNLICENSED - Private package for Generation One use only.

Details


Assets

  • api-generator-0.3.1.tgz

Download activity

  • Total downloads 15
  • Last 30 days 15
  • Last week 15
  • Today 0

Recent versions

View all