### Install Dependencies and Build Project Source: https://github.com/swagger-api/swagger-js/blob/master/CLAUDE.md Standard setup commands for installing project dependencies, building all targets, and running tests. Ensure the correct Node.js version is used. ```bash # Use correct Node.js version (see .nvmrc) nvm use # Install dependencies npm install # Build all targets npm run build # Run tests npm test ``` -------------------------------- ### File Upload Example (Browser) Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/tags-interface.md Demonstrates how to upload a file in a browser environment using a `Blob` object. ```APIDOC ## File Upload (Browser) ### Description Example of uploading a file in a browser environment using the `uploadFile` operation, creating a `Blob` object from an array of bytes and then accessing its stream. ### Method ```js client.apis.pet.uploadFile ``` ### Parameters #### Path Parameters None explicitly shown. #### Query Parameters None explicitly shown. #### Request Body - **petId** (number) - Required - The ID of the pet to upload the file for. - **file** (Blob.stream) - Required - The stream of the file blob to upload. ### Request Example ```html ``` ### Response #### Success Response - **Response** (object) - The response from the API call. ### Response Example ```js // Promise. ``` ``` -------------------------------- ### SwaggerClient Initialization with Options Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/tags-interface.md Example of initializing SwaggerClient with various configuration options, including disabling interfaces and compatibility modes. ```javascript import SwaggerClient from 'swagger-client'; new SwaggerClient({ url: 'http://petstore.swagger.io/v2/swagger.json', disableInterfaces: false, v2OperationIdCompatibilityMode: false, ...other options... }); ``` -------------------------------- ### Browser AbortController Example Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/tags-interface.md Shows how to use the native AbortController in a browser environment for cancelling Swagger JS requests. No external package installation is needed. ```html check console in browser's dev. tools ``` -------------------------------- ### Install Swagger Client via NPM Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/installation.md Use npm to install the swagger-client package. This is the standard method for Node.js and browser projects. ```shell $ npm install swagger-client ``` -------------------------------- ### Basic HTTP Client Configuration Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client-for-oas-operations.md Instantiate the HTTP client with the OpenAPI specification. This is the minimum required configuration to start making requests. ```javascript import { Swagger } from "@swagger-api/apic`; const client = new Swagger({ spec: require('./openapi.json') }); ``` -------------------------------- ### OpenAPI v3.x API Call Example with Options Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/tags-interface.md Demonstrates making an API call for an OpenAPI v3.x specification. This example highlights the use of an `Options` object to provide `requestBody`, `server` URL, and `serverVariables`, which are not direct parameters in v3.x. ```javascript import SwaggerClient from 'swagger-client'; new SwaggerClient({ spec, authorizations: { petstore_auth: { token: { access_token: '234934239' } } } }) .then(client => client .apis .pet // tag name == `pet` .addPet( // operationId == `addPet` { id: 1 }, { requestBody: { name: 'bobby', status: 'available', }, server: 'http://petstore.swagger.io/{apiPrefix}', // this should exactly match a URL in your `servers` serverVariables: { apiPrefix: 'v2' } } ) ); // => Promise. ``` -------------------------------- ### File Upload Example (Node.js) Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/tags-interface.md Illustrates how to upload a file using the `uploadFile` operation in a Node.js environment. ```APIDOC ## File Upload (Node.js) ### Description Example of uploading a file using the `uploadFile` operation in a Node.js environment, utilizing `fs.createReadStream`. ### Method ```js client.apis.pet.uploadFile ``` ### Parameters #### Path Parameters None explicitly shown. #### Query Parameters None explicitly shown. #### Request Body - **petId** (number) - Required - The ID of the pet to upload the file for. - **file** (Stream) - Required - The file stream to upload. ### Request Example ```js const fs = require('fs') const path = require('path') const myPetImage = fs.createReadStream(path.join(__dirname, 'myPet.jpg')) client.apis.pet.uploadFile({ petId: 256256, file: myPetImage }); ``` ### Response #### Success Response - **Response** (object) - The response from the API call. ### Response Example ```js // Promise. ``` ``` -------------------------------- ### Optimize NPM Installation with Overrides Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/installation.md Configure your package.json to use the 'overrides' field for faster installation by managing optional dependencies of ApiDOM. ```json "overrides": { "@swagger-api/apidom-reference": { "@swagger-api/apidom-ns-asyncapi-2": "npm:-@0.0.1", "@swagger-api/apidom-ns-asyncapi-3": "npm:-@0.0.1", "@swagger-api/apidom-ns-openapi-2": "npm:-@0.0.1", "@swagger-api/apidom-ns-openapi-3-0": "npm:-@0.0.1", "@swagger-api/apidom-ns-openapi-3-1": "npm:-@0.0.1", "@swagger-api/apidom-ns-openapi-3-2": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-api-design-systems-json": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-api-design-systems-yaml": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-asyncapi-json-2": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-asyncapi-json-3": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-asyncapi-yaml-2": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-asyncapi-yaml-3": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-json": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-openapi-json-2": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-openapi-yaml-2": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-openapi-json-3-0": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-openapi-json-3-1": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-openapi-json-3-2": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-openapi-yaml-3-0": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-openapi-yaml-3-1": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-openapi-yaml-3-2": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-arazzo-json-1": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-arazoo-yaml-1": "npm:-@0.0.1", "@swagger-api/apidom-parser-adapter-yaml-1-2": "npm:-@0.0.1" } } ``` -------------------------------- ### ESLint Import Order Example Source: https://github.com/swagger-api/swagger-js/blob/master/CLAUDE.md Demonstrates the correct order for import statements in JavaScript, separating external, internal, and relative modules. ```javascript // External dependencies import ramda from 'ramda'; import yaml from 'js-yaml'; // Internal modules import { makeHttp } from './http/index.js'; import { opId } from './helpers/index.js'; ``` -------------------------------- ### Query Parameter Support - Basic Example Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client.md Shows how to append query parameters to a request URL by providing a `query` object in the request configuration. The parameters are automatically serialized. ```javascript import SwaggerClient from 'swagger-client'; const request = { url: 'https://httpbin.org/?one=1&two=1', query: { two: { value: 2 }, three: { value: 3 } }, method: 'GET', }; SwaggerClient.http(request); // Requested URL: https://httpbin.org/?one=1&two=2&three=3 ``` -------------------------------- ### Adding Authorizations (2.x - ApiKey/Password) Source: https://github.com/swagger-api/swagger-js/blob/master/docs/migration/migration-2-x-to-3-x.md Example of adding authorizations using `ApiKeyAuthorization` and `PasswordAuthorization` in swagger-client 2.x. ```js const client = new Swagger('http://petstore.swagger.io/v2/swagger.json', { authorizations: { my_query_auth: new ApiKeyAuthorization('my-query', 'bar', 'query'), my_header_auth: new ApiKeyAuthorization('My-Header', 'bar', 'header'), my_basic_auth: new PasswordAuthorization('foo', 'bar'), cookie_: new CookieAuthorization('one=two') } }) ``` -------------------------------- ### Swagger Client Interface Example Source: https://github.com/swagger-api/swagger-js/blob/master/CLAUDE.md Demonstrates how to use the generated client interfaces for interacting with an OpenAPI specification. Supports both tag-based and operationId-based access. ```javascript const client = await Swagger('https://petstore.swagger.io/v2/swagger.json'); // Tag-based interface client.apis.pet.addPet({ body: petData }); // OperationId-based interface client.apis.addPet({ body: petData }); ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/swagger-api/swagger-js/blob/master/CLAUDE.md Examples of commit messages following the Conventional Commits specification, including type, scope, and subject. ```markdown feat(resolver): add support for OpenAPI 3.1 webhooks fix(http): handle empty response bodies correctly docs(README): update installation instructions test(execute): add test for parameter serialization chore(deps): bump @swagger-api/apidom-core to 1.0.0 ``` -------------------------------- ### HTTP Interceptor Example Source: https://github.com/swagger-api/swagger-js/blob/master/CLAUDE.md Shows how to configure request and response interceptors for the HTTP client. Interceptors allow for customization of requests and responses, such as adding authorization headers. ```javascript const client = await Swagger({ url: 'https://api.example.com/spec.json', requestInterceptor: (req) => { req.headers.Authorization = 'Bearer token'; return req; }, responseInterceptor: (res) => { console.log('Response:', res); return res; }, }); ``` -------------------------------- ### OpenAPI v2.x Add Pet Example Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/tags-interface.md Shows how to use the Tags Interface to call the `addPet` operation for OpenAPI v2.x definitions. ```APIDOC ## OpenAPI v2.x Add Pet ### Description Example of calling the `addPet` operation within the `pet` tag for an OpenAPI v2.x definition. ### Method ```js client.apis.pet.addPet ``` ### Parameters #### Path Parameters None explicitly shown. #### Query Parameters None explicitly shown. #### Request Body - **id** (number) - Required - The ID of the pet. - **body** (object) - Required - The pet object to add. - **name** (string) - Description of the name field. - **status** (string) - Description of the status field. ### Request Example ```js client.apis.pet.addPet({ id: 1, body: { name: 'bobby', status: 'available' } }); ``` ### Response #### Success Response - **Response** (object) - The response from the API call. ### Response Example ```js // Promise. ``` ``` -------------------------------- ### Options Override Example Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/tags-interface.md Demonstrates how to override request interceptors on a per-operation basis using the Options object. ```APIDOC ## Options Override ### Description Allows overriding options, such as `requestInterceptor`, for individual API operations by passing an `Options` object as the second argument to the callable operation. ### Example ```js new SwaggerClient({ url: 'http://petstore.swagger.io/v2/swagger.json', requestInterceptor: topLevelRequestInterceptor, }).then((client) => client.apis.user.getUserByName( { username: 'username' }, { requestInterceptor: interfaceLevelRequestInterceptor, } ) ); ``` ``` -------------------------------- ### OpenAPI v3.x Add Pet Example Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/tags-interface.md Demonstrates calling the `addPet` operation for OpenAPI v3.x definitions, including server variables and request body options. ```APIDOC ## OpenAPI v3.x Add Pet ### Description Example of calling the `addPet` operation within the `pet` tag for an OpenAPI v3.x definition, showcasing the use of an `Options` object for `requestBody`, `server`, and `serverVariables`. ### Method ```js client.apis.pet.addPet ``` ### Parameters #### Path Parameters - **id** (number) - Required - The ID of the pet. #### Query Parameters None explicitly shown. #### Options Object - **requestBody** (object) - Required - The pet object to add. - **name** (string) - Description of the name field. - **status** (string) - Description of the status field. - **server** (string) - Required - The server URL to use for the request. - **serverVariables** (object) - Optional - Variables for the server URL. - **apiPrefix** (string) - Example server variable. ### Request Example ```js client.apis.pet.addPet( { id: 1 }, { requestBody: { name: 'bobby', status: 'available', }, server: 'http://petstore.swagger.io/{apiPrefix}', serverVariables: { apiPrefix: 'v2' } } ); ``` ### Response #### Success Response - **Response** (object) - The response from the API call. ### Response Example ```js // Promise. ``` ``` -------------------------------- ### Query Parameter Support - Advanced Example Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client.md Illustrates advanced query parameter serialization, including arrays without a specified collection format and arrays with a specified `collectionFormat` like 'ssv'. ```javascript import SwaggerClient from 'swagger-client'; const request = { url: 'https://httpbin.org/', query: { anotherOne: ['one', 'two'], // no collection format evenMore: 'hi', // string, not an array bar: { collectionFormat: 'ssv', // supported values: csv, ssv, pipes value: [1, 2, 3] } }, method: 'GET', }; SwaggerClient.http(request); // Requested URL: https://httpbin.org/?anotherOne=one,two&evenMore=hi&bar=1%202%203 ``` -------------------------------- ### Node.js AbortController Example Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/tags-interface.md Demonstrates how to use AbortController in a Node.js environment to cancel Swagger JS requests. Requires the 'abort-controller' npm package. ```javascript const SwaggerClient = require('swagger-client'); const AbortController = require('abort-controller'); const controller = new AbortController(); const { signal } = controller; const timeout = setTimeout(() => { controller.abort(); }, 1); (async () => { try { await new SwaggerClient({ spec }) .then(client => client.apis.default.getUserList({}, { signal })) } catch (error) { if (error.name === 'AbortError') { console.error('request was aborted'); } } finally { clearTimeout(timeout); } })(); ``` -------------------------------- ### OpenAPI v2.x API Call Example Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/tags-interface.md Illustrates a basic API call using Swagger JS for an OpenAPI v2.x specification. It shows how to initialize the client with a URL and make a call to an operation like `addPet` within the `pet` tag. ```javascript import SwaggerClient from 'swagger-client'; new SwaggerClient({ url: 'http://petstore.swagger.io/v2/swagger.json', authorizations: { petstore_auth: { token: { access_token: '234934239' } } }, }) .then(client => client .apis .pet // tag name == `pet` .addPet({ // operationId == `addPet` id: 1, body: { name: 'bobby', status: 'available' } }) ); // => Promise. ``` -------------------------------- ### Embed Swagger Client via unpkg in HTML Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/installation.md Include the Swagger Client library directly in an HTML file using a CDN link from unpkg. This example demonstrates initializing the client and making an API call. ```html SwaggerClient test check console in browser's dev. tools ``` -------------------------------- ### Browser File Upload Example Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/tags-interface.md Demonstrates how to upload a file in a browser environment using Swagger JS. It involves creating a `Blob` object from an array of bytes and then calling the `uploadFile` operation with the blob's stream. ```html check console in browser's dev. tools ``` -------------------------------- ### Node.js File Upload Example Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/tags-interface.md Shows how to perform a file upload in a Node.js environment using Swagger JS. It utilizes the `fs` module to create a read stream for the file and passes it as the `file` parameter to the `uploadFile` operation. ```javascript const fs = require('fs') const path = require('path') const SwaggerClient = require('swagger-client'); const myPetImage = fs.createReadStream(path.join(__dirname, 'myPet.jpg')) SwaggerClient({ url: 'http://petstore.swagger.io/v2/swagger.json' }) .then(client => client.apis.pet.uploadFile({ petId: 256256, file: myPetImage })); // => Promise. ``` -------------------------------- ### Setting Default Content-Type (3.x) Source: https://github.com/swagger-api/swagger-js/blob/master/docs/migration/migration-2-x-to-3-x.md Provides a `requestInterceptor` example for swagger-client 3.x to manually set the `Content-Type` to `application/json` if not provided. ```js Swagger({ url: "http://petstore.swagger.io/v2/swagger.json", requestInterceptor: req => { if(req.body && !req.headers["Content-Type"]) { req.headers["Content-Type"] = "application/json" } } }) ``` -------------------------------- ### GitHub Actions Main Build Job Source: https://github.com/swagger-api/swagger-js/blob/master/CLAUDE.md Configuration for the main build job in the GitHub Actions workflow. It includes steps for setting up Node.js, installing dependencies, linting, testing, and building the project. ```yaml # In .github/workflows/nodejs.yml # Main Build Job (runs on Node.js 22, 24): # 1. Checkout code # 2. Setup Node.js # 3. Cache node_modules # 4. Install dependencies (`npm ci`) # 5. Lint commit message (commitlint) # 6. Lint code (`npm run lint`) # 7. Run tests (`npm test`) # 8. Build (`npm run build`) # 9. Upload build artifacts (Node 22 only) ``` -------------------------------- ### Get User List Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client-for-oas-operations.md Retrieves a list of users. This operation supports various authentication methods and accepts a query parameter for searching. ```APIDOC ## GET /users ### Description Get list of users. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters - **q** (array[string]) - Optional - search query parameter ### Responses #### Success Response (200) - **user** (object) - List of users ### Request Example ```json { "example": "request body" } ``` ### Response Example ```json { "example": "{\"id\":\"value\"}" } ``` -------------------------------- ### Custom Fetch with Axios Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client.md Override the default HTTP request behavior by providing a custom asynchronous function to `userFetch`. This example uses the axios library to make the request and returns a Fetch Compatible Response. ```javascript import SwaggerClient from 'swagger-client'; import axios from 'axios'; const request = { url: 'https://httpbin.org/', method: 'GET', userFetch: async (url, req) => { const axiosRequest = { ...req, data: req.body }; const axiosResponse = await axios(axiosRequest); return new Response(axiosResponse.data.data, { status: response.status, headers: response.headers, }); }, }; SwaggerClient.http(request); ``` -------------------------------- ### Unlink swagger-js and restore swagger-ui setup Source: https://github.com/swagger-api/swagger-js/blob/master/docs/development/setting-up.md After testing, unlink your local swagger-js from swagger-ui and restore the original 'predev' script in swagger-ui's package.json. This ensures the project is back to its default state. ```shell $ cd /path/to/swagger-ui $ npm unlink --no-save swagger-client $ npm install $ cd /path/to/swagger-js $ npm unlink ``` -------------------------------- ### Instantiate Swagger Client Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/api.md Demonstrates how to instantiate the Swagger Client using the constructor or as a function. Both methods are equivalent for initializing the client with an OpenAPI definition URL. ```javascript import SwaggerClient from 'swagger-client'; new SwaggerClient('http://petstore.swagger.io/v2/swagger.json'); SwaggerClient('http://petstore.swagger.io/v2/swagger.json'); // these two lines are equivalent ``` -------------------------------- ### SwaggerClient Constructor and Static Usage Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/api.md Demonstrates how to use the SwaggerClient, either by instantiating the constructor or by calling it as a function. Both methods are equivalent and implicitly instantiate the client. ```APIDOC ## SwaggerClient Usage ### Description This section covers the basic usage of the SwaggerClient, showing how to initialize it with an OpenAPI definition URL. It illustrates two equivalent ways to achieve this: using the `new` keyword to instantiate the client, or calling the `SwaggerClient` directly as a function. ### Method Constructor / Function Call ### Endpoint N/A (Client Initialization) ### Parameters - **url** (string) - Required - The URL of the OpenAPI definition file. ### Request Example ```js import SwaggerClient from 'swagger-client'; // Using the constructor new SwaggerClient('http://petstore.swagger.io/v2/swagger.json'); // Calling as a function (equivalent) SwaggerClient('http://petstore.swagger.io/v2/swagger.json'); ``` ### Response N/A (Client Initialization does not return a direct response in this context, but initializes the client instance.) ``` -------------------------------- ### Creating a Fetch Request Instance Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client.md Demonstrates creating a request using the `new Request()` constructor, which can be a native browser Request or from a library like cross-fetch. ```javascript const request = new Request('https://httpbin.org/post', { mode: 'cors', method: 'POST', body: { data: 3 }, headers: { 'Content-Type': 'application/json', }, }); ``` -------------------------------- ### Instantiating SwaggerClient with Callbacks (2.x) Source: https://github.com/swagger-api/swagger-js/blob/master/docs/migration/migration-2-x-to-3-x.md Illustrates the older callback-based instantiation method in swagger-client 2.x. ```js const client = new SwaggerClient({ success, failure, ...}); function success() { client.pet.addPet(...); } ``` -------------------------------- ### SwaggerClient Initialization Options Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/tags-interface.md Provides an overview of the options available when initializing SwaggerClient, which influence the behavior of the Tags Interface and request handling. ```APIDOC ## SwaggerClient Initialization ### Description Configure SwaggerClient with various options to customize its behavior, including disabling interfaces, compatibility modes, and interceptors. ### Options - `disableInterfaces` (Boolean=false): Disables the Tags Interface and the transformation of operationIds into callables. - `v2OperationIdCompatibilityMode` (Boolean=false): Uses an older algorithm for generating unique operationId names (kebab-case instead of camelCase). - `authorizations` (Object=undefined): Maps security schemes to requests. - `requestInterceptor` (Function=identity): A function to transform outgoing requests. - `responseInterceptor` (Function=identity): A function to transform incoming responses. - `userFetch` (Function=cross-fetch): A custom asynchronous fetch function. - `skipNormalization` (Boolean=false): Skips normalization that creates unique operationIds for duplicates. ### Request Example ```js import SwaggerClient from 'swagger-client'; new SwaggerClient({ url: 'http://petstore.swagger.io/v2/swagger.json', disableInterfaces: false, v2OperationIdCompatibilityMode: false, // ...other options... }); ``` ``` -------------------------------- ### Running Specific Tests with npm Source: https://github.com/swagger-api/swagger-js/blob/master/CLAUDE.md Commands to run specific test files or tests matching a pattern using npm. Also shows how to run tests with coverage. ```bash # Run specific test file npm run test:unit -- path/to/test.js # Run tests matching pattern npm run test:unit -- --testNamePattern="resolver" # Run with coverage npm run test:unit:coverage ``` -------------------------------- ### Opt out of Scarf Analytics via Environment Variable Source: https://github.com/swagger-api/swagger-js/blob/master/README.md Alternatively, you can disable Scarf analytics by setting the SCARF_ANALYTICS environment variable to 'false' before installing npm packages. ```bash SCARF_ANALYTICS=false npm install ``` -------------------------------- ### Opt out of Scarf Analytics in package.json Source: https://github.com/swagger-api/swagger-js/blob/master/README.md To opt out of anonymized installation analytics collected by Scarf, set the 'enabled' field to 'false' within the 'scarfSettings' object in your project's package.json file. ```json // package.json { // ... "scarfSettings": { "enabled": false } // ... } ``` -------------------------------- ### Run swagger-ui with linked swagger-client Source: https://github.com/swagger-api/swagger-js/blob/master/docs/development/setting-up.md After linking, run the swagger-ui development server to test your local swagger-client changes. This step requires temporarily removing the 'predev' script from swagger-ui's package.json. ```shell $ cd /path/to/swagger-ui $ npm run dev ``` -------------------------------- ### Providing a Custom HTTP Client Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client-for-oas-operations.md Replace the default HTTP client with a custom one using the `http` option. The custom client must adhere to the expected interface. ```javascript const customHttpClient = (request) => { // ... custom fetch logic ... return Promise.resolve(new Response('{}')); }; const client = new Swagger({ spec: require('./openapi.json'), http: customHttpClient }); ``` -------------------------------- ### Instantiating SwaggerClient with Promises (3.x) Source: https://github.com/swagger-api/swagger-js/blob/master/docs/migration/migration-2-x-to-3-x.md Shows the new promise-based instantiation for swagger-client 3.x. The client instance is resolved within the promise. ```js SwaggerClient({...}).then(client => { client.pet.addPet(...) }) ``` -------------------------------- ### Link swagger-js with swagger-ui for testing Source: https://github.com/swagger-api/swagger-js/blob/master/docs/development/setting-up.md This sequence of commands links your local swagger-js build into a swagger-ui project for testing purposes. Ensure you replace '/path/to/' with the actual directory paths. ```shell $ cd /path/to/swagger-js $ npm run build $ npm link $ cd /path/to/swagger-ui $ npm link swagger-client ``` -------------------------------- ### Call HTTP Client from SwaggerClient Instance Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client.md Illustrates how to access and use the HTTP client directly from a SwaggerClient instance. Requires an initialized SwaggerClient with a spec. ```javascript import SwaggerClient from 'swagger-client'; const { client } = new SwaggerClient({ spec: 'http://petstore.swagger.io/v2/swagger.json' }); client.http(request); ``` -------------------------------- ### POST Request with Request Object Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client.md Demonstrates how to make a POST HTTP request using the SwaggerClient.http method with a request object. ```javascript import SwaggerClient from 'swagger-client'; const request = { url: 'https://httpbin.org/post', mode: 'cors', method: 'POST', body: { data: 3 }, headers: { 'Content-Type': 'application/json', }, }; SwaggerClient.http(request); // => Promise(Response) ``` -------------------------------- ### Use Node.js version with NVM Source: https://github.com/swagger-api/swagger-js/blob/master/docs/development/setting-up.md If you are using nvm, this command automatically selects the correct Node.js version for the project. ```shell $ nvm use ``` -------------------------------- ### Instantiate SwaggerClient with URL Definition Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/openapi-definition-resolver.md Resolve OpenAPI definition from a URL during SwaggerClient instantiation. The resolved spec and any errors are available on the client instance. ```javascript import SwaggerClient from 'swagger-client'; new SwaggerClient('https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml').then(swaggerClient => { swaggerClient.spec; swaggerClient.errors; }); ``` -------------------------------- ### Setting a Base URL Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client-for-oas-operations.md Use the `baseURL` option to specify a URL that takes precedence over any server defined in the spec or the `server` option. It will be prepended to all request paths. ```javascript const client = new Swagger({ spec: require('./openapi.json'), baseURL: 'https://api.example.com/v1' }); ``` -------------------------------- ### Async/Await vs. Promises in JavaScript Source: https://github.com/swagger-api/swagger-js/blob/master/CLAUDE.md Compares the preferred async/await syntax with the traditional Promises `.then()` syntax for handling asynchronous operations in JavaScript. ```javascript // ✓ Preferred async function resolve(spec) { const result = await http.fetch(spec.url); return result; } // ✗ Avoid (unless chaining is cleaner) function resolve(spec) { return http.fetch(spec.url).then(result => result); } ``` -------------------------------- ### POST Request with URL and Request Object Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client.md Shows how to make a POST HTTP request using SwaggerClient.http by providing the URL as the first argument and the request object as the second, adhering to a Fetch-compatible interface. ```javascript import SwaggerClient from 'swagger-client'; const url = 'https://httpbin.org/post'; const request = { url, // notice the url must always be part of Request object mode: 'cors', method: 'POST', body: { data: 3 }, headers: { 'Content-Type': 'application/json', }, }; SwaggerClient.http(url, request); // => Promise(Response) ``` -------------------------------- ### Custom Fetch with Axios and Upload Progress Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client.md Demonstrates using a custom `userFetch` function with axios in a browser environment to track upload progress for POST requests. The `onUploadProgress` callback logs the completion percentage to the console. ```html check console in browser's dev. tools ``` -------------------------------- ### Calling Operations with Promises (3.x) Source: https://github.com/swagger-api/swagger-js/blob/master/docs/migration/migration-2-x-to-3-x.md Demonstrates calling operations using promises with `.then()` and `.catch()` in swagger-client 3.x. ```js client.apis.pet.findPetById({ petId: 3 }) .then(data => { /* success callback */}) .catch(error => {/* error callback */ }); ``` -------------------------------- ### Creating a Request Object Literal Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client.md Illustrates how to define a request using an object literal, which is compatible with the Fetch API's Request constructor. ```javascript const request = { url: 'https://httpbin.org/post', mode: 'cors', method: 'POST', body: { data: 3 }, headers: { 'Content-Type': 'application/json', }, }; ``` -------------------------------- ### Execute Operation Using Context URL Fallback Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client-for-oas-operations.md Use `contextUrl` as a fallback when no `Server Objects` are defined in the spec or when they are relative. This ensures requests can be made even with minimal server definitions. ```js SwaggerClient.execute({ spec: pojoDefinition, operationId: 'getUserList', parameters: { q: 'search string' }, securities: { authorized: { BearerAuth: "3492342948239482398" } }, server: '/', contextUrl: 'https://example.com', }); // => Promise. ``` -------------------------------- ### Instantiate SwaggerClient with POJO Definition Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/openapi-definition-resolver.md Resolve OpenAPI definition from a POJO during SwaggerClient instantiation. The resolved spec, original spec, and any errors are available on the client instance. ```javascript import SwaggerClient from 'swagger-client'; const pojoDefinition = { a: 1, b: { $ref: '#/a', } }; new SwaggerClient({ spec: pojoDefinition }).then(swaggerClient => { swaggerClient.spec; swaggerClient.originalSpec; swaggerClient.errors; }); ``` -------------------------------- ### Accessing Operations via Tags (2.x) Source: https://github.com/swagger-api/swagger-js/blob/master/docs/migration/migration-2-x-to-3-x.md Demonstrates the direct tag-based access to operations in swagger-client 2.x. ```js client.pet .findPetById(...); ``` -------------------------------- ### Execute Operation via SwaggerClient Instance Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client-for-oas-operations.md An alternate way to execute operations is by first creating a `SwaggerClient` instance and then calling its `execute` method. This approach is useful for repeated operations with the same client configuration. ```js import SwaggerClient from 'swagger-client'; new SwaggerClient({ spec: pojoDefinition, authorizations: { BearerAuth: "3492342948239482398" } }) .then( client => client.execute({ operationId: 'getUserList', parameters: { q: 'search string' }, }) ); // => Promise. ``` -------------------------------- ### JavaScript Import Extension Rule Source: https://github.com/swagger-api/swagger-js/blob/master/CLAUDE.md Illustrates the correct usage of file extensions in JavaScript import statements, emphasizing the requirement for `.js`. ```javascript import foo from './foo.js'; // ✓ Correct import foo from './foo'; // ✗ Wrong ``` -------------------------------- ### Adding Authorizations (3.x) Source: https://github.com/swagger-api/swagger-js/blob/master/docs/migration/migration-2-x-to-3-x.md Shows the updated authorization configuration for swagger-client 3.x, using a simpler object structure. Note that cookie authentication is not yet implemented. ```js Swagger('http://petstore.swagger.io/v2/swagger.json', { authorizations: { // Type of auth, is inferred from the specification provided my_basic_auth: { username: 'foo', password: 'bar' }, my_query_auth: 'foo', my_header_auth: 'foo', my_oauth2_token: { token: { access_token: 'abcabc' } }, cookie_auth: null, // !!Not implemented } }).then( client => ... ); ``` -------------------------------- ### Cancel Request with AbortSignal in Browser Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client-for-oas-operations.md Shows how to cancel a request in a browser environment using the native `AbortController`. The `signal` is passed to `SwaggerClient.execute`. Errors are caught and logged if the request is aborted. ```html check console in browser's dev. tools ``` -------------------------------- ### Composing Multiple Request Interceptors with Pipe Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client.md Illustrates how to chain multiple request interceptors using a pipe function to sequentially modify the request object. ```javascript import SwaggerClient from 'swagger-client'; const pipeP = (...fns) => args => fns.reduce((arg, fn) => arg.then(fn), Promise.resolve(args)) const interceptor1 = req => { req.url += '?param1=value1'; return req; } const interceptor2 = async req => { req.url += '¶m2=value2'; return Promise.resolve(req); }; const request = { url: 'https://httpbin.org/', method: 'GET', requestInterceptor: pipeP(interceptor1, interceptor2), }; SwaggerClient.http(request); // Requested URL: https://httpbin.org/?param1=value1¶m2=value2 ``` -------------------------------- ### Prettier Configuration JSON Source: https://github.com/swagger-api/swagger-js/blob/master/CLAUDE.md Configuration settings for Prettier, defining code formatting rules like print width, tab size, and semicolon usage. ```json { "printWidth": 100, "tabWidth": 2, "semi": true, "singleQuote": true, "trailingComma": "es5" } ``` -------------------------------- ### Platform-Specific Imports Source: https://github.com/swagger-api/swagger-js/blob/master/CLAUDE.md Illustrates how platform-specific imports are handled using conditional resolution configured in `package.json`. This allows different code paths for browser and Node.js environments. ```javascript // In source code import btoa from './helpers/btoa.node.js'; // In browser, webpack resolves to import btoa from './helpers/btoa.browser.js'; ``` -------------------------------- ### Node.js HTTP Server Implementation Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client-for-oas-operations.md This Node.js code implements a basic HTTP server that handles requests according to the defined API paths. It includes a handler for the '/users' path to retrieve a list of users. ```javascript const http = require('http'); const getUserList = (req, res) => { res.setHeader('Content-Type', 'application/json'); res.writeHead(200); res.end('[{"id":"value"}]'); }; const requestListener = (req, res) => { if (req.url.startsWith('/users')) { getUserList(req, res); } else { res.setHeader('Content-Type', 'text/plain'); res.writeHead(404); res.end('Not found'); } }; const server = http.createServer(requestListener); server.listen(8080); ``` -------------------------------- ### Cancel HTTP Request with AbortSignal in Node.js Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client.md Demonstrates how to cancel an HTTP request using AbortController in a Node.js environment. Requires the 'abort-controller' package. ```javascript const SwaggerClient = require('swagger-client'); const AbortController = require('abort-controller'); const controller = new AbortController(); const { signal } = controller; const timeout = setTimeout(() => { controller.abort(); }, 1); (async () => { try { await SwaggerClient.http({ url: 'https://www.google.com', signal }); } catch (error) { if (error.name === 'AbortError') { console.error('request was aborted'); } } finally { clearTimeout(timeout); } })(); ``` -------------------------------- ### Fixing a Bug Workflow Source: https://github.com/swagger-api/swagger-js/blob/master/CLAUDE.md Outlines the steps for fixing a bug, including writing a failing test, identifying the affected module, fixing the code, and verifying the fix. ```bash # Commit with proper format: fix(module): description ``` -------------------------------- ### Adding Authorizations (2.x - clientAuthorizations) Source: https://github.com/swagger-api/swagger-js/blob/master/docs/migration/migration-2-x-to-3-x.md Alternative method in swagger-client 2.x for adding authorizations via `clientAuthorizations.add`. ```js const client = new Swagger('http://petstore.swagger.io/v2/swagger.json', ...) // Basic Auth client.clientAuthorizations.add('my_query_auth', new ApiKeyAuthorization('my-query', 'bar', 'query')) client.clientAuthorizations.add('my_header_auth', new ApiKeyAuthorization('My-Header', 'bar', 'header')) client.clientAuthorizations.add('my_basic_auth', new PasswordAuthorization('foo', 'bar')) client.clientAuthorizations.add('cookie', new CookieAuthorization('one=two')) ``` -------------------------------- ### Execute Operation Using Server Option Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client-for-oas-operations.md Specify a particular server to send requests to by using the `server` option. This is helpful when the OpenAPI definition includes multiple server objects. ```js SwaggerClient.execute({ spec: pojoDefinition, operationId: 'getUserList', parameters: { q: 'search string' }, securities: { authorized: { BearerAuth: "3492342948239482398" } }, server: 'http://localhost:8080', }); // => Promise. ``` -------------------------------- ### Enable CORS Globally Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client.md Activate Cross-Origin Resource Sharing (CORS) for all HTTP client requests by setting `SwaggerClient.http.withCredentials` to `true`. This implicitly sets `credentials="include"` for every request. ```javascript import SwaggerClient from 'swagger-client'; SwaggerClient.http.withCredentials = true; ``` -------------------------------- ### Request Cancellation with AbortSignal Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/tags-interface.md Explains how to cancel API requests using the `AbortController` and `AbortSignal` for implementing features like request timeouts. ```APIDOC ## Request Cancellation with AbortSignal ### Description This section describes how to cancel API requests using the standard Web API `AbortController` and `AbortSignal`. This is useful for implementing features such as request timeouts. ### Usage Pass an `AbortSignal` object within the `Options` object of a callable operation. The request will be aborted if the `AbortSignal`'s `abort()` method is called. ### Example ```js const controller = new AbortController(); const signal = controller.signal; client.someOperation({ param: 'value' }, { signal: signal }) .catch(error => { if (error.name === 'AbortError') { console.log('Request was aborted'); } }); // To cancel the request: // controller.abort(); ``` ``` -------------------------------- ### Using a Custom Fetch Function Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client-for-oas-operations.md Provide a custom asynchronous `userFetch` function for making requests. This function should accept a URL and a Request object, returning a Promise that resolves to a Response object. ```javascript const customFetch = async (url, request) => { // ... custom fetch logic using fetch API ... const response = await fetch(url, request); return response; }; const client = new Swagger({ spec: require('./openapi.json'), userFetch: customFetch }); ``` -------------------------------- ### Configuring Security Schemes Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client-for-oas-operations.md Define security schemes for requests using the `securities` object. This maps security scheme names from your spec to their corresponding credentials or tokens. ```javascript const response = await client.execute({ operationId: 'protectedOperation', securities: { authorized: { BearerAuth: { value: '3492342948239482398' } } } }); ``` -------------------------------- ### JavaScript Named and Default Exports Source: https://github.com/swagger-api/swagger-js/blob/master/CLAUDE.md Shows the recommended pattern for exporting modules in JavaScript, using named exports for individual functions and a default export for the main module. ```javascript // Named exports export const resolve = () => {}; export const execute = () => {}; // Default export for main module export default Swagger; ``` -------------------------------- ### Instantiate SwaggerClient with URL Object Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/openapi-definition-resolver.md Resolve OpenAPI definition from a URL object during SwaggerClient instantiation. The resolved spec and any errors are available on the client instance. ```javascript import SwaggerClient from 'swagger-client'; new SwaggerClient({ url: 'https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml' }).then(swaggerClient => { swaggerClient.spec; swaggerClient.errors; }); ``` -------------------------------- ### Calling Operations with Callbacks (2.x) Source: https://github.com/swagger-api/swagger-js/blob/master/docs/migration/migration-2-x-to-3-x.md Shows how operations were called using success and error callbacks in swagger-client 2.x. ```js client.apis.pet .findPetById( { petId: 3 }, data => { /* success callback */}, error => { /* error callback */ } ); ``` -------------------------------- ### Passing Parameters to an Operation Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/http-client-for-oas-operations.md Provide parameters for an operation using the `parameters` object. Only parameters defined in the OpenAPI specification for the operation will be used; others are ignored. ```javascript const response = await client.execute({ operationId: 'findUsers', parameters: { query: { q: 'search string' } } }); ``` -------------------------------- ### Accessing Response Body (3.x) Source: https://github.com/swagger-api/swagger-js/blob/master/docs/migration/migration-2-x-to-3-x.md Illustrates the new key name `response.body` for the parsed response body in swagger-client 3.x. ```js function print(response) { // print out the parsed object console.log(response.body); } ``` -------------------------------- ### Import Swagger Client in ES6 Source: https://github.com/swagger-api/swagger-js/blob/master/docs/usage/installation.md Import the SwaggerClient class using ES6 import syntax for use in modern JavaScript environments. ```javascript import SwaggerClient from 'swagger-client'; ```