### ng-openapi-gen Configuration File Example Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Example of an ng-openapi-gen.json configuration file. The $schema property enables IDE auto-completion. ```json { "$schema": "node_modules/ng-openapi-gen/ng-openapi-gen-schema.json", "input": "openapi.yaml", "output": "src/app/api", "promises": true, "services": false, "apiService": "Api", "enumStyle": "alias", "enumArray": true, "ignoreUnusedModels": true, "removeStaleFiles": true, "includeTags": ["Users", "Products"], "excludeTags": ["Internal"], "excludePaths": ["/health", "/metrics"], "modelPrefix": "", "modelSuffix": "", "serviceSuffix": "Service", "module": false, "indexFile": true, "endOfLineStyle": "lf" } ``` -------------------------------- ### Install and Generate from Local Spec (CLI) Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Install the package globally and use the CLI to generate API client code from a local OpenAPI YAML file. The output directory defaults to src/app/api. ```bash # Global install npm install -g ng-openapi-gen # Generate from a local YAML file ng-openapi-gen --input my-api.yaml --output src/app/api ``` -------------------------------- ### ng-openapi-gen Configuration File Example Source: https://github.com/cyclosproject/ng-openapi-gen/blob/master/README.md Example of a JSON configuration file for ng-openapi-gen. The 'input' property is required, specifying the OpenAPI specification file. 'output' defaults to 'src/app/api'. ```json { "$schema": "node_modules/ng-openapi-gen/ng-openapi-gen-schema.json", "input": "my-file.json", "output": "my-app/src/app/api", "ignoreUnusedModels": false } ``` -------------------------------- ### Install ng-openapi-gen Globally Source: https://github.com/cyclosproject/ng-openapi-gen/blob/master/README.md Install the ng-openapi-gen package globally using npm. This allows you to use the command-line interface directly. ```bash $ npm install -g ng-openapi-gen $ ng-openapi-gen --input my-api.yaml --output my-app/src/app/api ``` -------------------------------- ### Configure npm Scripts for API Generation Source: https://github.com/cyclosproject/ng-openapi-gen/blob/master/README.md Set up npm scripts in `package.json` to automatically generate API code before starting or building your project. This ensures generated files are up-to-date. ```json { "scripts": { "generate:api": "ng-openapi-gen", "start": "npm run generate:api && npm run ng -- serve", "build": "npm run generate:api && npm run ng -- build -prod" } } ``` -------------------------------- ### Configure Customized Response Types Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Use this configuration to specify the response type for particular paths. This is useful when auto-detection fails, for example, with binary downloads. ```json { "input": "openapi.yaml", "output": "src/app/api", "customizedResponseType": { "/files/{id}/download": { "toUse": "blob" }, "/reports/{id}/export": { "toUse": "arraybuffer" }, "/embed/{id}": { "toUse": "document" } } } ``` -------------------------------- ### Run ng-openapi-gen Programmatically Source: https://github.com/cyclosproject/ng-openapi-gen/blob/master/README.md Use ng-openapi-gen directly within your TypeScript build scripts. This example shows how to load and bundle an OpenAPI specification before generating the API client. ```typescript import $RefParser from 'json-schema-ref-parser'; import { NgOpenApiGen } from 'ng-openapi-gen'; const options = { input: "my-api.json", output: "my-app/src/app/api", } // load the openapi-spec and resolve all $refs const RefParser = new $RefParser(); const openApi = await RefParser.bundle(options.input, { dereference: { circular: false } }); const ngOpenGen = new NgOpenApiGen(openApi, options); gOpenGen.generate(); ``` -------------------------------- ### Use Generated API with Services Source: https://github.com/cyclosproject/ng-openapi-gen/blob/master/README.md Example of using the generated API client with services, which is an alternative to functional calls. This approach injects a service (e.g., 'ResultsService') that encapsulates API operations. ```typescript import { Component, inject, OnInit, signal } from '@angular/core'; import { RouterOutlet } from '@angular/router'; import { Result } from './api/models'; import { ResultsService } from './api/services'; @Component({ selector: 'app-root', imports: [RouterOutlet], templateUrl: './app.html', styleUrl: './app.css', }) export class App implements OnInit { protected readonly results = signal(null); private resultsService = inject(ResultsService); async ngOnInit() { this.results.set(await this.resultsService.getResults({ limit: 5 })); } } ``` -------------------------------- ### NPM Scripts for Automated API Generation Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Integrate ng-openapi-gen into your NPM scripts to automatically regenerate API client code before starting the application, building, or testing. ```json { "scripts": { "generate:api": "ng-openapi-gen", "generate:api:users": "ng-openapi-gen -c api-users.json", "generate:api:payments": "ng-openapi-gen -c api-payments.json", "generate:all": "npm run generate:api:users && npm run generate:api:payments", "start": "npm run generate:all && ng serve", "build": "npm run generate:all && ng build --configuration production", "test": "npm run generate:all && ng test" } } ``` -------------------------------- ### Use Generated API with Functional Calls Source: https://github.com/cyclosproject/ng-openapi-gen/blob/master/README.md Example of using the generated API client within an Angular component. This approach uses the injected 'Api' service and specific operation functions like 'getResults'. ```typescript import { Component, inject, OnInit, signal } from '@angular/core'; import { RouterOutlet } from '@angular/router'; import { Api } from './api/api'; import { getResults } from './api/fn/operations/get-results'; import { Result } from './api/models'; @Component({ selector: 'app-root', imports: [RouterOutlet], templateUrl: './app.html', styleUrl: './app.css', }) export class App implements OnInit { protected readonly results = signal(null); private api = inject(Api); async ngOnInit() { this.results.set(await this.api.invoke(getResults, { limit: 5 })); } } ``` -------------------------------- ### Show All Options (CLI) Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Display all available command-line options and their descriptions for ng-openapi-gen. ```bash # Show all options ng-openapi-gen --help ``` -------------------------------- ### Top-Level Entry Point for CLI Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt The runNgOpenApiGen() function serves as the main entry point for the ng-openapi-gen binary. It handles CLI arguments, spec fetching, and generation. ```typescript import { runNgOpenApiGen } from 'ng-openapi-gen'; // Equivalent to running `ng-openapi-gen` from the command line. // Reads process.argv and ng-openapi-gen.json automatically. runNgOpenApiGen().catch(err => { console.error('Generation failed:', err); process.exit(1); }); ``` -------------------------------- ### Short Flags for Generation (CLI) Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Utilize short flags (-i for input, -o for output) for quicker command-line generation of API client code. ```bash # Short flags (-i / -o) ng-openapi-gen -i my-api.json -o src/app/api ``` -------------------------------- ### Configure API Root URL with provideApiConfiguration Source: https://github.com/cyclosproject/ng-openapi-gen/blob/master/README.md Use this method in your application's providers list to set the API root URL. Ensure you import `provideApiConfiguration`. ```typescript import { ApplicationConfig } from '@angular/core'; import { provideApiConfiguration } from './api/api-configuration'; export const appConfig: ApplicationConfig = { providers: [ // ...other providers... provideApiConfiguration('http://localhost:3000/api') ] }; ``` -------------------------------- ### Using the generated `Api` service (Promise mode) Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Demonstrates how to use the generated `Api` service in Promise mode. The `api.invoke()` method is used to call API functions, and `api.invoke$Response()` provides access to the full HTTP response, including status and headers. ```APIDOC ## Using the generated `Api` service (Promise mode) After generation the main entry point is the injectable `Api` class. Pass the imported function and its parameters to `api.invoke()`. ```typescript import { Component, inject, OnInit, signal } from '@angular/core'; import { Api } from './api/api'; import { listUsers } from './api/fn/users/list-users'; import { getUser } from './api/fn/users/get-user'; import { createUser } from './api/fn/users/create-user'; import type { User } from './api/models'; @Component({ selector: 'app-users', standalone: true, template: ``, }) export class UsersComponent implements OnInit { private api = inject(Api); readonly users = signal([]); async ngOnInit() { // Call without parameters (optional params) this.users.set(await this.api.invoke(listUsers)); // Call with parameters const user = await this.api.invoke(getUser, { id: 42 }); console.log(user.name); // Access full HTTP response (status, headers) const resp = await this.api.invoke$Response(createUser, { body: { name: 'Alice', email: 'alice@example.com' } }); console.log(resp.status); // 201 console.log(resp.body); // User } } ``` ``` -------------------------------- ### Using Custom Handlebars Helpers in Templates Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Demonstrates how to use custom helpers like 'upper' and 'prefixed' within a Handlebars template to generate dynamic constants. ```handlebars {{! Usage inside a custom template }} export const {{upper typeName}}_KEY = '{{prefixed "api_" typeName}}'; ``` -------------------------------- ### Programmatic API Usage Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Instantiate the NgOpenApiGen class with parsed OpenAPI data and options, then call generate() to produce client code. This is useful for build scripts. ```typescript import $RefParser from '@apidevtools/json-schema-ref-parser'; import { NgOpenApiGen } from 'ng-openapi-gen'; async function generateClient() { const refParser = new $RefParser(); // Parse (without full dereferencing so $refs stay intact) const openApi = await refParser.parse('openapi.yaml', { resolve: { http: { timeout: 20000 } } }); const options = { input: 'openapi.yaml', output: 'src/app/api', promises: true, services: false, apiService: 'Api', enumStyle: 'alias' as const, enumArray: true, ignoreUnusedModels: true, removeStaleFiles: true, }; const gen = new NgOpenApiGen(openApi as any, options); gen.generate(); // Output: Generation from openapi.yaml finished with N models and M services. } generateClient().catch(console.error); ``` -------------------------------- ### Using the generated `Api` service (Observable mode) Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Illustrates how to use the generated `Api` service when configured for Observable mode (`"promises": false`). The `api.invoke()` method returns an Observable, and `api.invoke$Response()` returns an Observable of the full HTTP response. ```APIDOC ## Using the generated `Api` service (Observable mode) Set `"promises": false` in configuration to get Observable-based methods. ```typescript import { Component, inject, OnInit } from '@angular/core'; import { AsyncPipe } from '@angular/common'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { Api } from './api/api'; import { listProducts } from './api/fn/products/list-products'; import type { Product } from './api/models'; @Component({ selector: 'app-products', standalone: true, imports: [AsyncPipe], template: `
{{ p.name }}
`, }) export class ProductsComponent implements OnInit { private api = inject(Api); products$!: Observable; ngOnInit() { // invoke() returns Observable when promises: false this.products$ = this.api.invoke(listProducts, { limit: 20 }); // Full response observable this.api.invoke$Response(listProducts, { limit: 20 }).pipe( map(r => r.body) ).subscribe(products => console.log(products)); } } ``` ``` -------------------------------- ### Use Configuration File (CLI) Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Specify a custom configuration file for ng-openapi-gen to use, overriding CLI flags. The default configuration file is ng-openapi-gen.json in the current working directory. ```bash # Use a config file (defaults to ng-openapi-gen.json in CWD) ng-openapi-gen --config my-config.json ``` -------------------------------- ### Configuring the Root URL with ApiConfiguration Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Three methods are provided to set the API base URL at runtime: using a provider function (recommended for Angular 17+), injecting and mutating the configuration at bootstrap, or via the Api service instance. ```typescript // 1. Provider function (recommended, Angular 17+) // app.config.ts import { ApplicationConfig } from '@angular/core'; import { provideHttpClient } from '@angular/common/http'; import { provideApiConfiguration } from './api/api-configuration'; export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(), provideApiConfiguration('https://api.example.com/v1'), ], }; ``` ```typescript // 2. Inject and mutate at bootstrap import { Component, inject, OnInit } from '@angular/core'; import { ApiConfiguration } from './api/api-configuration'; @Component({ selector: 'app-root', standalone: true, template: '' }) export class AppComponent implements OnInit { private apiConfig = inject(ApiConfiguration); ngOnInit() { this.apiConfig.rootUrl = 'https://api.example.com/v1'; } } ``` ```typescript // 3. Via the Api service instance import { Component, inject } from '@angular/core'; import { Api } from './api/api'; @Component({ selector: 'app-root', standalone: true, template: '' }) export class AppComponent { private api = inject(Api); constructor() { this.api.rootUrl = 'https://staging.example.com/v1'; } } ``` -------------------------------- ### Configure Multiple API Generation Tasks Source: https://github.com/cyclosproject/ng-openapi-gen/blob/master/README.md If you use multiple OpenAPI specifications, define separate generation scripts and a master `generate:api` script to run them sequentially. This allows for managing different API configurations. ```json { "scripts": { "generate:api": "npm run generate:api:a && npm run generate:api:b", "generate.api:a": "ng-openapi-gen -c api-a.json", "generate.api:b": "ng-openapi-gen -c api-b.json", "start": "npm run generate:api && npm run ng -- serve", "build": "npm run generate:api && npm run ng -- build -prod" } } ``` -------------------------------- ### Generate from Remote URL (CLI) Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Use the CLI to generate API client code from a remote OpenAPI JSON specification URL. The output directory defaults to src/app/api. ```bash # Generate from a remote URL ng-openapi-gen --input https://petstore3.swagger.io/api/v3/openapi.json --output src/app/api ``` -------------------------------- ### Registering Custom Handlebars Helper Source: https://github.com/cyclosproject/ng-openapi-gen/blob/master/README.md Integrate custom Handlebars helpers by providing a `handlebars.js` file that exports a function to register helpers with the Handlebars instance. ```javascript module.exports = function(handlebars) { // Adding a custom handlebars helper: loud handlebars.registerHelper('loud', function (aString) { return aString.toUpperCase() }); }; ``` -------------------------------- ### ng-openapi-gen Configuration Options Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt This section outlines the various configuration options available for ng-openapi-gen, which map directly to CLI flags and JSON config file keys. These options control input sources, output paths, file filtering, naming conventions, code style, and advanced generation settings. ```APIDOC ## `Options` interface — full configuration reference Every property of the `Options` interface maps directly to a CLI flag and a key in the JSON config file. ```typescript import type { Options } from 'ng-openapi-gen'; const options: Options = { // Required input: 'https://api.example.com/openapi.json', // Output output: 'src/app/api', // default: 'src/app/api' removeStaleFiles: true, // delete files no longer generated useTempDir: false, // write to system tmp dir during generation indexFile: true, // emit a barrel index.ts // Filtering includeTags: ['Users', 'Orders'], excludeTags: ['Deprecated'], excludePaths: ['/internal/ping'], ignoreUnusedModels: true, // Naming modelPrefix: '', modelSuffix: '', servicePrefix: '', serviceSuffix: 'Service', configuration: 'ApiConfiguration', baseService: 'BaseService', apiService: 'Api', // false = skip; string = custom name requestBuilder: 'RequestBuilder', response: 'StrictHttpResponse', module: false, // false = no NgModule; true = 'ApiModule' camelizeModelNames: true, // Code style promises: true, // false → Observables services: false, // true → generate per-tag service classes enumStyle: 'alias', // 'alias' | 'upper' | 'pascal' | 'ignorecase' enumArray: true, // emit sibling *-array.ts files for enums endOfLineStyle: 'lf', // 'lf' | 'crlf' | 'cr' | 'auto' skipJsonSuffix: false, // Advanced fetchTimeout: 20000, templates: 'src/templates', // directory with custom .handlebars overrides defaultTag: 'Api', excludeParameters: ['X-Request-ID'], customizedResponseType: { '/files/{id}': { toUse: 'blob' }, }, keepFullResponseMediaType: false, silent: false, }; ``` ``` -------------------------------- ### Using Generated Per-Tag Service Classes Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Enable `services: true` to generate `@Injectable` wrapper classes grouped by OpenAPI tag. All tag operations are available as methods on the service. Use the `$Response` variant for headers or status access. ```typescript import { Component, inject, OnInit, signal } from '@angular/core'; import { UsersService } from './api/services/users.service'; import type { User } from './api/models'; @Component({ selector: 'app-user-detail', standalone: true, template: `

{{ user()?.name }}

`, }) export class UserDetailComponent implements OnInit { private usersService = inject(UsersService); readonly user = signal(null); async ngOnInit() { // All tag operations available as methods on the service const user = await this.usersService.getUser({ id: 1 }); this.user.set(user); await this.usersService.updateUser({ id: 1, body: { name: 'Bob', email: 'bob@example.com' } }); // $Response variant for headers / status access const resp = await this.usersService.deleteUser$Response({ id: 1 }); console.log(resp.status); // 204 } } ``` -------------------------------- ### Registering Custom Handlebars Helpers Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Create a 'handlebars.js' file alongside your templates to register custom helpers. These helpers can be used within your Handlebars templates for dynamic content generation. ```javascript // src/templates/handlebars.js module.exports = function (handlebars) { // Uppercase helper handlebars.registerHelper('upper', str => (str || '').toUpperCase()); // Prefix helper handlebars.registerHelper('prefixed', (prefix, name) => prefix + name); // Conditional type check handlebars.registerHelper('isString', type => type === 'string'); }; ``` -------------------------------- ### Linking Local ng-openapi-gen Build Source: https://github.com/cyclosproject/ng-openapi-gen/blob/master/README.md After building the generator locally, use `npm link` in the `dist` directory to link the compiled version for testing with other Node.js projects. ```bash npm run build cd dist npm link ``` -------------------------------- ### ng-openapi-gen Configuration for Custom Templates Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Configure ng-openapi-gen to use your custom templates by specifying the 'templates' directory in the configuration file. ```json { "$schema": "node_modules/ng-openapi-gen/ng-openapi-gen-schema.json", "input": "openapi.yaml", "output": "src/app/api", "templates": "src/templates" } ``` -------------------------------- ### Using Generated API Service (Observable Mode) Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Configure `promises: false` to use Observable-based API methods. The `api.invoke()` method returns an Observable, and `api.invoke$Response()` allows piping to access the full HTTP response. ```typescript import { Component, inject, OnInit } from '@angular/core'; import { AsyncPipe } from '@angular/common'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { Api } from './api/api'; import { listProducts } from './api/fn/products/list-products'; import type { Product } from './api/models'; @Component({ selector: 'app-products', standalone: true, imports: [AsyncPipe], template: `
{{ p.name }}
`, }) export class ProductsComponent implements OnInit { private api = inject(Api); products$!: Observable; ngOnInit() { // invoke() returns Observable when promises: false this.products$ = this.api.invoke(listProducts, { limit: 20 }); // Full response observable this.api.invoke$Response(listProducts, { limit: 20 }).pipe( map(r => r.body) ).subscribe(products => console.log(products)); } } ``` -------------------------------- ### OpenAPI Vendor Extensions for Operation Names and Enums Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Utilize OpenAPI vendor extensions like 'x-operation-name' for shorter method names and 'x-enumNames' for custom enum labels to improve generated code clarity. ```yaml # x-operation-name: shorter per-tag method name (LoopBack style) paths: /users: get: tags: [Users] operationId: listUsers # globally unique x-operation-name: list # short name used in UsersService.list() responses: '200': description: OK /orders: get: tags: [Orders] operationId: listOrders x-operation-name: list # same short name, different service responses: '200': description: OK # x-enumNames: custom labels for integer enums (NSwag style) components: schemas: HttpStatusCode: type: integer enum: [200, 404, 500] x-enumNames: [OK, NOT_FOUND, INTERNAL_SERVER_ERROR] # Generates: # export type HttpStatusCode = 200 | 404 | 500; # export const HttpStatusCodeArray = [200, 404, 500]; # With pascal style: OK = 200, NotFound = 404, InternalServerError = 500 ``` -------------------------------- ### Create an HTTP Interceptor for API Requests Source: https://github.com/cyclosproject/ng-openapi-gen/blob/master/README.md Define an `HttpInterceptorFn` to intercept and modify outgoing HTTP requests. This is useful for adding headers or handling errors centrally. ```typescript import { HttpInterceptorFn } from '@angular/common/http'; export const API_INTERCEPTOR: HttpInterceptorFn = (req, next) => { console.log('Intercepted request:', req); return next(req); }; ``` -------------------------------- ### Set API Root URL by Injecting ApiConfiguration Source: https://github.com/cyclosproject/ng-openapi-gen/blob/master/README.md Inject the `ApiConfiguration` instance in your bootstrap component and set its `rootUrl` property. This is useful for dynamic configuration. ```typescript import { Component, inject, OnInit, signal } from '@angular/core'; import { RouterOutlet } from '@angular/router'; import { ApiConfiguration } from './api/api-configuration'; import { Result } from './api/models'; @Component({ selector: 'app-root', imports: [RouterOutlet], templateUrl: './app.html', styleUrl: './app.css', }) export class App implements OnInit { protected readonly results = signal(null); private apiConfiguration = inject(ApiConfiguration); async ngOnInit() { this.apiConfiguration.rootUrl = 'http://localhost:3000/api'; } } ``` -------------------------------- ### ng-openapi-gen Options Interface Configuration Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Configure the OpenAPI generator using the Options interface. This object maps directly to CLI flags and JSON config file keys. Ensure all required properties like 'input' are provided. ```typescript import type { Options } from 'ng-openapi-gen'; const options: Options = { // Required input: 'https://api.example.com/openapi.json', // Output output: 'src/app/api', // default: 'src/app/api' removeStaleFiles: true, // delete files no longer generated useTempDir: false, // write to system tmp dir during generation indexFile: true, // emit a barrel index.ts // Filtering includeTags: ['Users', 'Orders'], excludeTags: ['Deprecated'], excludePaths: ['/internal/ping'], ignoreUnusedModels: true, // Naming modelPrefix: '', modelSuffix: '', servicePrefix: '', serviceSuffix: 'Service', configuration: 'ApiConfiguration', baseService: 'BaseService', apiService: 'Api', // false = skip; string = custom name requestBuilder: 'RequestBuilder', response: 'StrictHttpResponse', module: false, // false = no NgModule; true = 'ApiModule' camelizeModelNames: true, // Code style promises: true, // false → Observables services: false, // true → generate per-tag service classes enumStyle: 'alias', // 'alias' | 'upper' | 'pascal' | 'ignorecase' enumArray: true, // emit sibling *-array.ts files for enums endOfLineStyle: 'lf', // 'lf' | 'crlf' | 'cr' | 'auto' skipJsonSuffix: false, // Advanced fetchTimeout: 20000, templates: 'src/templates', // directory with custom .handlebars overrides defaultTag: 'Api', excludeParameters: ['X-Request-ID'], customizedResponseType: { '/files/{id}': { toUse: 'blob' }, }, keepFullResponseMediaType: false, silent: false, }; ``` -------------------------------- ### Custom Interface Template with BaseModel Extension Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Use this Handlebars template to make all generated interfaces extend a BaseModel. Place it in your project and reference it via the 'templates' config key. ```handlebars {{! src/templates/object.handlebars — makes every generated interface extend BaseModel }} import { BaseModel } from 'src/app/core/base-model'; export interface {{typeName}} extends BaseModel { {{#properties}} {{{tsComments}}}{{{identifier}}}{{#unless required}}?{{/unless}}: {{{type}}}; {{/properties}} {{#additionalPropertiesType}} [key: string]: {{{.}}}; {{/additionalPropertiesType}} } ``` -------------------------------- ### Generated Function Respects Blob Override Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt This TypeScript code demonstrates how a generated function respects the 'blob' override for response types. Ensure the `downloadFile` function is imported correctly. ```typescript // Generated function respects the blob override import { downloadFile } from './api/fn/files/download-file'; const response = await api.invoke$Response(downloadFile, { id: '123' }); const blob: Blob = response.body; const url = URL.createObjectURL(blob); ``` -------------------------------- ### OpenAPI Vendor Extension: x-enumNames Source: https://github.com/cyclosproject/ng-openapi-gen/blob/master/README.md The `x-enumNames` extension allows customization of enum names in generated code. It must be an array of strings with the same length as the `enum` values. ```yaml components: schemas: HttpStatusCode: type: integer enum: - 200 - 404 - 500 x-enumNames: - OK - NOT_FOUND - INTERNAL_SERVER_ERROR ``` -------------------------------- ### Enum Styles: alias, pascal, and upper Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Control OpenAPI enum emission with `enumStyle` and `enumArray`. The default `alias` style produces zero-overhead union types with an iterable array sidecar. Other styles include `pascal` and `upper`. ```json // ng-openapi-gen.json // { "enumStyle": "alias", "enumArray": true } ``` ```typescript // Generated: src/app/api/models/order-status.ts export type OrderStatus = 'pending' | 'confirmed' | 'shipped' | 'delivered' | 'cancelled'; ``` ```typescript // Generated sidecar: src/app/api/models/order-status-array.ts import { OrderStatus } from './order-status'; export const OrderStatusArray: OrderStatus[] = ['pending', 'confirmed', 'shipped', 'delivered', 'cancelled']; ``` ```json // --- // { "enumStyle": "pascal" } ``` ```typescript // Generated: src/app/api/models/order-status.ts export enum OrderStatus { Pending = 'pending', Confirmed = 'confirmed', Shipped = 'shipped', } ``` ```json // --- // { "enumStyle": "upper" } ``` ```typescript export enum OrderStatus { PENDING = 'pending', CONFIRMED = 'confirmed', SHIPPED = 'shipped', } ``` -------------------------------- ### Using Generated API Service (Promise Mode) Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Inject and use the generated `Api` service in Angular components for Promise-based API calls. Use `api.invoke()` for data retrieval and `api.invoke$Response()` to access full HTTP responses including status and headers. ```typescript import { Component, inject, OnInit, signal } from '@angular/core'; import { Api } from './api/api'; import { listUsers } from './api/fn/users/list-users'; import { getUser } from './api/fn/users/get-user'; import { createUser } from './api/fn/users/create-user'; import type { User } from './api/models'; @Component({ selector: 'app-users', standalone: true, template: `
    @for (u of users(); track u.id) {
  • {{ u.name }}
  • }
`, }) export class UsersComponent implements OnInit { private api = inject(Api); readonly users = signal([]); async ngOnInit() { // Call without parameters (optional params) this.users.set(await this.api.invoke(listUsers)); // Call with parameters const user = await this.api.invoke(getUser, { id: 42 }); console.log(user.name); // Access full HTTP response (status, headers) const resp = await this.api.invoke$Response(createUser, { body: { name: 'Alice', email: 'alice@example.com' } }); console.log(resp.status); // 201 console.log(resp.body); // User } } ``` -------------------------------- ### OpenAPI Vendor Extension: x-operation-name Source: https://github.com/cyclosproject/ng-openapi-gen/blob/master/README.md Use the `x-operation-name` extension to specify a custom method name for an operation within a tag. This is useful for providing shorter, more convenient names than the default `operationId`. ```yaml paths: /users: get: tags: - Users operationId: listUsers x-operation-name: list # ... /places: get: tags: - Places operationId: listPlaces x-operation-name: list # ... ``` -------------------------------- ### Register HTTP Interceptor in Angular Application Source: https://github.com/cyclosproject/ng-openapi-gen/blob/master/README.md Provide the custom HTTP interceptor in your `app.config.ts` using `provideHttpClient` and `withInterceptors`. Ensure `API_INTERCEPTOR` is imported. ```typescript import { ApplicationConfig } from '@angular/core'; import { provideHttpClient, withInterceptors } from '@angular/common/http'; import { API_INTERCEPTOR } from './api-interceptor'; export const appConfig: ApplicationConfig = { providers: [ // ... others provideHttpClient(withInterceptors([API_INTERCEPTOR])), ], }; ``` -------------------------------- ### Filter OpenAPI Paths Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt The filterPaths() function allows pre-filtering of OpenAPI paths based on include/exclude tags and paths. It operates on a deep copy of the paths object. ```typescript import { filterPaths } from 'ng-openapi-gen'; import type { PathsObject } from 'openapi-types'; const allPaths: PathsObject = { '/users': { get: { tags: ['Users'], operationId: 'listUsers', responses: {} }, }, '/admin/settings': { get: { tags: ['Admin'], operationId: 'getSettings', responses: {} }, }, '/health': { get: { tags: ['System'], operationId: 'health', responses: {} }, }, }; // Keep only Users tag, exclude /health path const filtered = filterPaths( allPaths, ['Admin'], // excludeTags ['/health'], // excludePaths ['Users'], // includeTags ); console.log(Object.keys(filtered)); // Output: ['/users'] ``` -------------------------------- ### Customizing Object Templates in Handlebars Source: https://github.com/cyclosproject/ng-openapi-gen/blob/master/README.md Customize the `object.handlebars` template to extend generated interfaces with a base model. Ensure the template path is correctly configured in `ng-openapi-gen.json`. ```handlebars import { MyBaseModel} from 'src/app/my-base-model'; export interface {{typeName}} extends MyBaseModel { {{#properties}} {{{tsComments}}}{{{identifier}}}{{^required}}?{{/required}}: {{{type}}}; {{/properties}} {{#additionalPropertiesType}} [key: string]: {{{.}}}; {{/additionalPropertiesType}} } ``` -------------------------------- ### HTTP Interceptors for Auth Tokens and Error Handling Source: https://context7.com/cyclosproject/ng-openapi-gen/llms.txt Standard Angular functional interceptors can be used for authentication tokens and centralized error handling without requiring changes to the generated code. The interceptor should be provided in `app.config.ts`. ```typescript // api-interceptor.ts import { HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http'; import { inject } from '@angular/core'; import { catchError, throwError } from 'rxjs'; import { AuthService } from './auth.service'; export const apiInterceptor: HttpInterceptorFn = (req, next) => { const auth = inject(AuthService); const token = auth.getToken(); const authReq = token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req; return next(authReq).pipe( catchError((err: HttpErrorResponse) => { if (err.status === 401) auth.logout(); return throwError(() => err); }) ); }; ``` ```typescript // app.config.ts import { ApplicationConfig } from '@angular/core'; import { provideHttpClient, withInterceptors } from '@angular/common/http'; import { apiInterceptor } from './api-interceptor'; export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(withInterceptors([apiInterceptor])), ], }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.