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
A command-line tool for generating TypeScript API clients from OpenAPI schemas.
- 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
# Install from G1 package registry
npm install @g1/api-generator --save-dev
# Or with pnpm
pnpm add @g1/api-generator -D
# 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
{
"scripts": {
"api:generate": "g1-api-generator https://localhost:7205/openapi/schema.json src/lib/api"
}
}
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);
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
The package includes comprehensive examples demonstrating various usage patterns:
-
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
# View the example file
cat examples/factory-pattern-usage.ts
# Run examples (after generating a client)
npx ts-node examples/factory-pattern-usage.ts
When you specify a clientName
, the generator creates a factory pattern that allows you to create multiple client instances with different endpoint configurations:
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();
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
});
The factory pattern supports different authentication and security systems through request interception:
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();
// 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()
]);
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'
});
Version 0.3.0 introduces factory pattern support for multiple endpoint configurations. Here's how to migrate:
-
Regenerate your API client with a client name:
g1-api-generator https://your-api-server/openapi/schema.json ./src/lib/api --client-name ApiClient
-
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' });
-
Benefits of the factory pattern:
- Support for multiple client instances with different endpoints
- Cleaner configuration interface
- Better TypeScript support
- Future-proof architecture
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' });
The tool automatically applies the following post-processing to the generated code:
- Removes import statements for
void
type - Replaces usages of
void
as a type withany
- Detects and replaces self-referencing DTOs with
any
- Adds auto-generated comments to files
- Generates factory class when
clientName
is provided
UNLICENSED - Private package for Generation One use only.
Details
- api-generator
-
Generation-One
- 1 day ago
- UNLICENSED
- 4 dependencies
Assets
- api-generator-0.3.1.tgz
Download activity
- Total downloads 15
- Last 30 days 15
- Last week 15
- Today 0