### Initializing with Minimal Setup Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/06-module-exports.md Demonstrates the simplest way to initialize the default swell client and perform a GET request. ```typescript import { swell } from 'swell-node'; swell.init('store', 'key'); const data = await swell.get('/endpoint'); ``` -------------------------------- ### X-User-Application Header Example Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/04-configuration.md Example of the header format generated when npm package environment variables are present. ```text X-User-Application: my-app@1.2.3 ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/00-index.md Example .env file configuration for store credentials and client settings. ```bash # .env SWELL_STORE_ID=my-store SWELL_API_KEY=secret-key SWELL_TIMEOUT=15000 SWELL_RETRIES=3 ``` -------------------------------- ### GET with No Parameters Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/07-http-methods.md Examples of fetching all, single, or related resources without additional query parameters. ```typescript // Fetch all products const allProducts = await client.get('/products'); // Fetch single resource const product = await client.get('/products/product-123'); // Fetch related resources const reviews = await client.get('/products/product-123/reviews'); ``` -------------------------------- ### Initialize Client with Custom Options Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/02-types.md Example of instantiating a new Client with specific timeout, retry, and lifecycle callback configurations. ```typescript const client = new Client('my-store', 'key', { timeout: 10000, // 10 second timeout retries: 3, // Retry 3 times on network errors maxSockets: 50, // Limit concurrent connections recycleAfterRequests: 2000, // Recycle after 2000 requests recycleAfterMs: 30000, // Or after 30 seconds headers: { 'X-Custom-Header': 'value' }, onRequestComplete: (stats) => { console.log(`Request took ${stats.durationMs}ms`); }, onClientRecycle: (stats) => { console.log(`Client recycled: ${stats.totalRequests} requests`); } }); ``` -------------------------------- ### Read Products with GET Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/05-usage-patterns.md Retrieves a list of resources with optional filtering and pagination parameters. ```typescript // Get all products const result = await client.get('/products', { limit: 20, offset: 0, active: true }); console.log('Products:', result.results); console.log('Total:', result.count); ``` -------------------------------- ### HTTP Basic Authentication Header Example Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/10-authentication.md Demonstrates the manual construction of the Base64 encoded Authorization header. ```text Store ID: my-store API Key: secret-key-123 Combined: my-store:secret-key-123 Base64: bXktc3RvcmU6c2VjcmV0LWtleS0xMjM= Header: Authorization: Basic bXktc3RvcmU6c2VjcmV0LWtleS0xMjM= ``` -------------------------------- ### Read Single Product with GET Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/05-usage-patterns.md Fetches a specific resource by its unique identifier. ```typescript const product = await client.get('/products/product-id-123'); console.log('Product name:', product.name); ``` -------------------------------- ### Importing with TypeScript Types Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/06-module-exports.md Example of importing the library with explicit type definitions for configuration. ```typescript import { swell, Client, ClientOptions, RequestStats, HttpHeaders } from 'swell-node'; const options: ClientOptions = { timeout: 10000, onRequestComplete: (stats: RequestStats) => { console.log(stats); }, headers: { 'X-App': 'myapp' } as HttpHeaders }; const client = new Client('my-store', 'key', options); ``` -------------------------------- ### Performing HTTP Requests Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/07-http-methods.md Examples of using the request method for GET, POST, PUT, and DELETE operations. ```typescript import { Client, HttpMethod } from 'swell-node'; const client = new Client('my-store', 'key'); // GET const products = await client.request(HttpMethod.get, '/products'); // POST const created = await client.request(HttpMethod.post, '/products', { name: 'Item', price: 29.99 }); // PUT const updated = await client.request(HttpMethod.put, '/products/123', { price: 39.99 }); // DELETE const deleted = await client.request(HttpMethod.delete, '/products/123'); ``` -------------------------------- ### Install Swell Node library Source: https://github.com/swellstores/swell-node/blob/master/README.md Use npm to add the swell-node package to your project dependencies. ```bash npm install swell-node --save ``` -------------------------------- ### get(url, data, headers) Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/01-client-class.md Makes a GET HTTP request to the Swell API. Query parameters can be passed via the data object. ```APIDOC ## get(url, data, headers) ### Description Makes a GET HTTP request to the Swell API. The data parameter is converted to a query string. ### Parameters - **url** (string) - Required - API endpoint path. - **data** (unknown) - Optional - Query parameters. - **headers** (HttpHeaders) - Optional - Additional HTTP headers. ``` -------------------------------- ### Simple GET Request Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/07-http-methods.md Basic usage of the GET method to fetch resources without parameters. ```typescript const products = await client.get('/products'); console.log('Products:', products); ``` -------------------------------- ### Perform GET requests with the Swell client Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/01-client-class.md Use the get method to retrieve resources, optionally passing query parameters or custom headers. ```typescript get( url: string, data?: unknown, headers?: HttpHeaders ): Promise ``` ```typescript const client = new Client('my-store', 'key'); // Simple GET request const response = await client.get('/products'); // GET with query parameters const products = await client.get('/products', { active: true, limit: 10 }); // GET with custom headers const data = await client.get('/products', {}, { 'X-Custom-Header': 'value' }); ``` -------------------------------- ### Implement onClientRecycle callback Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/04-configuration.md Examples for logging client recycling events and tracking recycle counts. ```typescript const client = new Client('my-store', 'key', { recycleAfterRequests: 1000, recycleAfterMs: 15000, onClientRecycle: (stats) => { console.log( `Client recycled: ${stats.totalRequests} requests, ` + `age: ${(stats.ageMs / 1000).toFixed(1)}s, ` + `active: ${stats.activeRequests}` ); } }); ``` ```typescript let recycleCount = 0; const client = new Client('my-store', 'key', { onClientRecycle: (stats) => { recycleCount++; console.log(`Client #{recycleCount} recycled after ${stats.totalRequests} requests`); } }); ``` -------------------------------- ### GET Method Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/07-http-methods.md The GET method is used to retrieve resources from the API without modifying state. It supports query parameters, custom headers, and generic typing for response data. ```APIDOC ## GET [url] ### Description Retrieve data from the API without modifying any state. Query parameters are converted from objects to URL query strings. ### Method GET ### Parameters #### Path Parameters - **url** (string) - Required - API endpoint path (e.g., '/products') #### Query Parameters - **data** (unknown) - Optional - Query parameters or filter criteria #### Request Headers - **headers** (HttpHeaders) - Optional - Additional HTTP headers for this request ### Response - **Promise** - Resolves to the response data (generic type T) ### Examples ```typescript // Simple GET const products = await client.get('/products'); // GET with Query Parameters const response = await client.get('/products', { limit: 20, active: true }); // GET with Custom Headers const product = await client.get('/products/123', {}, { 'X-Include-Hidden': 'true' }); ``` ``` -------------------------------- ### swell.get(path) Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/01-client-class.md Performs a GET request to the specified API path using the initialized client. ```APIDOC ## swell.get(path) ### Description Sends a GET request to the Swell API. ### Parameters - **path** (string) - Required - The API endpoint path (e.g., '/products'). ### Example ```typescript const products = await swell.get('/products'); ``` ``` -------------------------------- ### Implement onRequestComplete callback Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/04-configuration.md Examples for logging request metrics and calculating average response times. ```typescript const client = new Client('my-store', 'key', { onRequestComplete: (stats) => { console.log( `${stats.method.toUpperCase()} ${stats.url} ` + `(${stats.attempts} attempt(s), ${stats.durationMs}ms, ` + `${stats.success ? 'OK' : 'FAILED'})` ); } }); ``` ```typescript let totalRequests = 0; let totalDuration = 0; const client = new Client('my-store', 'key', { onRequestComplete: (stats) => { totalRequests++; totalDuration += stats.durationMs; const avgDuration = totalDuration / totalRequests; console.log(`Average response time: ${avgDuration.toFixed(2)}ms`); } }); ``` -------------------------------- ### Retry Backoff Execution Example Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/09-retry-logic.md Illustrates the sequence of attempts and delays when a request fails with a retryable error like ECONNREFUSED. ```typescript const client = new Client('my-store', 'key', { retries: 3 }); // If request fails with ECONNREFUSED: // Attempt 1: 0ms // Wait: ~50ms (random 20-100ms) // Attempt 2: ~50ms // Wait: ~50ms // Attempt 3: ~100ms // Wait: ~50ms // Attempt 4: ~150ms // Fails: Throws error try { await client.get('/products'); } catch (error) { // Total time: ~150-200ms, made 4 attempts (1 initial + 3 retries) } ``` -------------------------------- ### init(clientId, clientKey, options) Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/01-client-class.md Initializes or reinitializes the client with specific store credentials and configuration settings. ```APIDOC ## init(clientId, clientKey, options) ### Description Configures the client with the necessary store credentials. This method can be called on an existing client to update its configuration. ### Parameters - **clientId** (string) - Required - Store ID for authentication. - **clientKey** (string) - Required - API key for authentication. - **options** (ClientOptions) - Optional - Configuration options to be merged with defaults. ### Returns - **void** ``` -------------------------------- ### GET with Custom Headers Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/07-http-methods.md Passing custom HTTP headers to the GET request. ```typescript const product = await client.get('/products/123', {}, { 'X-Include-Hidden': 'true' }); ``` -------------------------------- ### Initialize Client Instance Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/01-client-class.md Demonstrates creating a client instance either uninitialized or with credentials immediately. ```typescript import { Client } from 'swell-node'; // Create an uninitialized client const client = new Client(); client.init('my-store', 'secret-key', { timeout: 5000 }); // Create and initialize in one step const client = new Client('my-store', 'secret-key', { timeout: 5000, retries: 3 }); ``` -------------------------------- ### GET Method Signature Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/07-http-methods.md The generic signature for the GET method used to retrieve resources. ```typescript get( url: string, data?: unknown, headers?: HttpHeaders ): Promise ``` -------------------------------- ### Configuring Full-Featured Client Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/06-module-exports.md Shows how to instantiate a custom Client with specific options, including timeouts, retries, and request tracking. ```typescript import { Client, ClientOptions, HttpMethod, RequestStats } from 'swell-node'; const options: ClientOptions = { timeout: 10000, retries: 3, onRequestComplete: (stats: RequestStats) => { console.log(`${stats.method} took ${stats.durationMs}ms`); } }; const client = new Client('store', 'key', options); await client.request(HttpMethod.get, '/products'); ``` -------------------------------- ### Initialize Client with init() Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/01-client-class.md Configures or reconfigures an existing client instance with store credentials and custom options. ```typescript const client = new Client(); // Initialize with minimal options client.init('my-store', 'secret-key'); // Initialize with custom configuration client.init('my-store', 'secret-key', { timeout: 10000, retries: 3, verifyCert: false }); ``` -------------------------------- ### Initialize Client via Init Method Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/10-authentication.md Instantiate the client first and provide credentials later using the init method. ```typescript const client = new Client(); client.init('my-store', 'secret-key'); ``` -------------------------------- ### Initialize Swell Client Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/05-usage-patterns.md Demonstrates different ways to initialize the client, including singleton, instance-based, and configuration-heavy approaches. ```typescript import { swell } from 'swell-node'; // Initialize once at application startup swell.init('my-store', 'secret-key'); // Use throughout application const products = await swell.get('/products'); const newProduct = await swell.post('/products', { name: 'Item', price: 29.99 }); ``` ```typescript import { Client } from 'swell-node'; const client = new Client('my-store', 'secret-key'); const products = await client.get('/products'); ``` ```typescript import { Client } from 'swell-node'; const client = new Client('my-store', 'secret-key', { timeout: 10000, retries: 3, maxSockets: 100, onRequestComplete: (stats) => { console.log(`${stats.method} ${stats.url}: ${stats.durationMs}ms`); } }); const products = await client.get('/products'); ``` -------------------------------- ### Initialize Client with Configuration Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/10-authentication.md Provide additional configuration options like timeout and retries during client instantiation. ```typescript const client = new Client('my-store', 'secret-key', { timeout: 10000, retries: 3 }); ``` -------------------------------- ### Initialize Client with .env File Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/10-authentication.md Load credentials from a .env file using the dotenv package. ```typescript // .env SWELL_STORE_ID=my-store SWELL_API_KEY=secret-key-abc123 // app.ts import 'dotenv/config'; const client = new Client( process.env.SWELL_STORE_ID!, process.env.SWELL_API_KEY! ); ``` -------------------------------- ### Typed GET Request Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/07-http-methods.md Using TypeScript generics to define the expected response structure. ```typescript interface Product { id: string; name: string; price: number; } interface ListResponse { results: T[]; count: number; } const response = await client.get>('/products'); response.results.forEach(p => console.log(p.name)); ``` -------------------------------- ### swell.init(storeId, secretKey) Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/01-client-class.md Initializes the singleton client instance with the store ID and secret key required for authentication. ```APIDOC ## swell.init(storeId, secretKey) ### Description Initializes the singleton client instance. This must be called before making any API requests. ### Parameters - **storeId** (string) - Required - The ID of the store. - **secretKey** (string) - Required - The secret key for authentication. ### Example ```typescript import { swell } from 'swell-node'; swell.init('my-store', 'secret-key'); ``` ``` -------------------------------- ### Initialize Client with Environment Variables Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/10-authentication.md Initialize the client directly using environment variables or with fallback values for local development. ```typescript const client = new Client( process.env.SWELL_STORE_ID, process.env.SWELL_API_KEY ); ``` ```typescript const storeId = process.env.SWELL_STORE_ID || 'default-store'; const apiKey = process.env.SWELL_API_KEY || 'default-key'; const client = new Client(storeId, apiKey); ``` -------------------------------- ### Handle API Errors Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/02-types.md Example of catching and accessing properties from an ApiError when a request fails. ```typescript import { Client } from 'swell-node'; const client = new Client('my-store', 'key'); try { await client.get('/products/nonexistent'); } catch (error) { if (error instanceof Error) { const err = error as any; // ApiError properties console.log('Error:', err.message); console.log('Code:', err.code); console.log('Status:', err.status); console.log('Headers:', err.headers); } } ``` -------------------------------- ### Create Product with POST Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/05-usage-patterns.md Sends a POST request to create a new resource. ```typescript const newProduct = await client.post('/products', { name: 'New Product', description: 'Product description', price: 29.99, active: true }); console.log('Created product:', newProduct.id); ``` -------------------------------- ### Retryable error scenarios Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/09-retry-logic.md Examples of network-level failures that trigger the automatic retry mechanism. ```typescript const client = new Client('my-store', 'key', { retries: 3 }); // These errors trigger automatic retries: try { await client.get('/products'); // If server is temporarily down } catch (error) { // Retried 3 times, then failed } try { await client.get('/products'); // If network is flaky } catch (error) { // Retried 3 times, then failed } ``` -------------------------------- ### ClientOptions (Interface) Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/06-module-exports.md Configuration options for the Client constructor and init() method. ```APIDOC ## ClientOptions (Interface) ### Description Configuration options for the Client constructor and init() method. ``` -------------------------------- ### Create a fully initialized client Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/08-api-client-lifecycle.md Pass configuration parameters to the constructor to initialize the HTTP client immediately. ```typescript const client = new Client('my-store', 'secret-key', { timeout: 10000, maxSockets: 100 }); // HTTP client is created immediately console.log(client.httpClient); // AxiosInstance ``` -------------------------------- ### Conditional DELETE Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/07-http-methods.md Perform a delete operation only after verifying the resource state via a GET request. ```typescript const product = await client.get('/products/prod-123'); if (product.inventory <= 0 && !product.active) { await client.delete(`/products/${product.id}`); console.log('Archived old inactive product'); } ``` -------------------------------- ### Managing Multiple Stores Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/06-module-exports.md Illustrates how to create and use multiple independent client instances for different stores. ```typescript import { swell } from 'swell-node'; const store1 = swell.createClient('store-1', 'key-1'); const store2 = swell.createClient('store-2', 'key-2'); const [p1, p2] = await Promise.all([ store1.get('/products'), store2.get('/products') ]); ``` -------------------------------- ### GET with Query Parameters Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/07-http-methods.md Passing query parameters as an object to filter or limit the API response. ```typescript const response = await client.get('/products', { limit: 20, offset: 0, active: true, sort: '-created_at' }); console.log('Results:', response.results); console.log('Total count:', response.count); ``` -------------------------------- ### Initialize Client via Constructor Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/10-authentication.md Instantiate the client by passing the store ID and API key directly to the constructor. ```typescript const client = new Client('my-store', 'secret-key'); ``` -------------------------------- ### HttpMethod (Enum) Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/06-module-exports.md Defines the supported HTTP methods (get, post, put, delete) for the client. ```APIDOC ## HttpMethod (Enum) ### Description Defines the supported HTTP methods for the client. ### Values - get - post - put - delete ``` -------------------------------- ### Initialize Swell Client with Configuration Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/04-configuration.md Full configuration object for the Swell client, including network, pooling, retry, and monitoring hooks. ```typescript import { Client } from 'swell-node'; const client = new Client('my-store', 'secret-key', { // Network configuration url: 'https://api.swell.store', timeout: 10000, verifyCert: true, // Connection pooling maxSockets: 100, keepAliveMs: 1000, // Retry strategy retries: 3, // Client recycling recycleAfterRequests: 1000, recycleAfterMs: 15000, // Custom headers headers: { 'X-Request-ID': 'my-app', 'X-Api-Version': 'v1' }, // Monitoring onRequestComplete: (stats) => { console.log(`${stats.method.toUpperCase()} ${stats.url} - ${stats.durationMs}ms`); }, onClientRecycle: (stats) => { console.log(`Client recycled after ${stats.totalRequests} requests`); } }); ``` -------------------------------- ### constructor(clientId, clientKey, options) Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/01-client-class.md Initializes a new instance of the Swell API client. Can be used to create an uninitialized client or one fully configured with store credentials. ```APIDOC ## constructor(clientId, clientKey, options) ### Description Creates a new Client instance. If credentials are provided, the client is initialized immediately. ### Parameters - **clientId** (string) - Optional - Store ID for authentication. - **clientKey** (string) - Optional - API key for authentication. - **options** (ClientOptions) - Optional - Configuration options for the client. ### Returns - **Client** - A new Client instance. ``` -------------------------------- ### Initialize Production Client Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/00-index.md Configures the client with production-grade settings including timeouts, retries, and request monitoring. ```typescript const client = new Client( process.env.SWELL_STORE_ID!, process.env.SWELL_API_KEY!, { timeout: 15000, retries: 3, maxSockets: 100, verifyCert: process.env.NODE_ENV === 'production', headers: { 'X-App': process.env.npm_package_name, 'X-Version': process.env.npm_package_version }, onRequestComplete: (stats) => { if (!stats.success || stats.durationMs > 5000) { logger.warn('Slow/failed request', stats); } } } ); ``` -------------------------------- ### Configure and use the Client class Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/README.md Instantiate a custom Client with specific options like timeouts, retries, and request lifecycle hooks. ```typescript import { Client, ClientOptions } from 'swell-node'; const client = new Client('my-store', 'secret-key', { timeout: 10000, retries: 3, maxSockets: 100, onRequestComplete: (stats) => { console.log(`${stats.method} ${stats.url}: ${stats.durationMs}ms`); }, onClientRecycle: (stats) => { console.log(`Client recycled after ${stats.totalRequests} requests`); } }); // Make requests const response = await client.get('/products', { limit: 20 }); console.log('Products:', response.results); ``` -------------------------------- ### Connect to Swell API Source: https://github.com/swellstores/swell-node/blob/master/README.md Initialize the client using your store ID and secret key. Use createClient for managing multiple store connections simultaneously. ```javascript const { swell } = require('swell-node'); swell.init('my-store', 'secret-key'); ``` ```javascript const { swell } = require('swell-node'); const client1 = swell.createClient('my-store-1', 'secret-key-1'); const client2 = swell.createClient('my-store-2', 'secret-key-2'); ``` -------------------------------- ### Authenticated HTTP Methods Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/10-authentication.md The Authorization header is applied to all HTTP methods including GET, POST, PUT, and DELETE. ```typescript const client = new Client('my-store', 'key'); // GET - includes Authorization await client.get('/products'); // POST - includes Authorization await client.post('/products', { name: 'Item' }); // PUT - includes Authorization await client.put('/products/123', { price: 29.99 }); // DELETE - includes Authorization await client.delete('/products/123'); ``` -------------------------------- ### Initialize the client manually Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/08-api-client-lifecycle.md Use the init method to configure and create the HTTP client instance after instantiation. ```typescript const client = new Client(); client.init('my-store', 'secret-key', { timeout: 10000, maxSockets: 100 }); // Now the HTTP client is created console.log(client.httpClient); // AxiosInstance ``` -------------------------------- ### Initialize and use the global swell client Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/README.md Initialize the library with store credentials and perform standard CRUD operations. ```typescript import { swell } from 'swell-node'; // Initialize once swell.init('my-store', 'secret-key'); // Use throughout your application const products = await swell.get('/products'); const newProduct = await swell.post('/products', { name: 'Item', price: 29.99 }); const updated = await swell.put('/products/123', { price: 39.99 }); await swell.delete('/products/123'); ``` -------------------------------- ### Perform a Simple API Request Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/00-index.md Use this pattern to fetch data from a specific endpoint using the client's get method. ```typescript try { const data = await client.get('/products/123'); console.log('Product:', data.name); } catch (error) { console.error('Error:', (error as any).message); } ``` -------------------------------- ### Initialize Client with Recycling Options Source: https://github.com/swellstores/swell-node/blob/master/copilot-instructions.md Configure custom thresholds for HTTP connection recycling and monitor recycling events via a callback. ```typescript // Example usage with recycling options const client = new Client('store-id', 'key', { recycleAfterRequests: 500, recycleAfterMs: 10000, onClientRecycle: (stats) => console.log('Client recycled:', stats) }); ``` -------------------------------- ### Initialize Client for Constrained Environments Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/00-index.md Configures the client for Docker or Kubernetes environments with lower socket limits and request recycling. ```typescript const client = new Client( process.env.SWELL_STORE_ID, process.env.SWELL_API_KEY, { maxSockets: 50, // Constrained environments recycleAfterRequests: 500 } ); ``` -------------------------------- ### Client.post(url, data, headers?) Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/00-index.md Creates a new resource at the specified URL. ```APIDOC ## POST [url] ### Description Creates a new resource at the specified URL. ### Method POST ### Parameters #### Path Parameters - **url** (string) - Required - The resource path for creation. #### Request Body - **data** (object) - Required - The data payload for the new resource. #### Headers - **headers** (object) - Optional - Custom headers for the request. ``` -------------------------------- ### Import the Client class Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/06-module-exports.md Import the main HTTP client class for manual instantiation. ```typescript import { Client } from 'swell-node'; ``` -------------------------------- ### Import the swell singleton Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/06-module-exports.md Import the pre-instantiated singleton client. ```typescript import { swell } from 'swell-node'; ``` -------------------------------- ### Client Initialization Errors Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/03-errors.md Errors thrown during the client.init() process when required parameters are missing. ```APIDOC ## client.init(id, key) ### Description Initializes the Swell API client. Throws an error if the store ID or API key is missing, null, or an empty string. ### Errors - **Swell store 'id' is required to connect**: Thrown when the store ID is undefined, null, or an empty string. - **Swell store 'key' is required to connect**: Thrown when the API key is undefined, null, or an empty string. ``` -------------------------------- ### Initialize and use Swell client Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/00-index.md Initialize the singleton client once at startup to perform CRUD operations across the application. ```typescript import { swell } from 'swell-node'; // Initialize once at startup swell.init('my-store', 'secret-key'); // Use throughout application const products = await swell.get('/products'); const newProduct = await swell.post('/products', { name: 'Item', price: 29.99 }); const updated = await swell.put('/products/123', { price: 39.99 }); await swell.delete('/products/123'); ``` -------------------------------- ### Bulk Create with Loop Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/07-http-methods.md Creating multiple resources sequentially using a loop. ```typescript const items = [ { name: 'Item 1', price: 10 }, { name: 'Item 2', price: 20 }, { name: 'Item 3', price: 30 } ]; const created = []; for (const item of items) { const result = await client.post('/products', item); created.push(result); } console.log('Created', created.length, 'products'); ``` -------------------------------- ### Configure Client for Testing and Development Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/08-api-client-lifecycle.md Uses aggressive recycling settings to facilitate testing of the client lifecycle. ```typescript const client = new Client('my-store', 'key', { recycleAfterRequests: 10, // Frequent for testing recycleAfterMs: 2000, onClientRecycle: (stats) => { console.log('[TEST] Client recycled'); } }); ``` -------------------------------- ### Configure client options Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/06-module-exports.md Pass a configuration object to the client constructor to set timeouts and retry logic. ```typescript import { Client, ClientOptions } from 'swell-node'; const options: ClientOptions = { timeout: 10000, retries: 3, maxSockets: 100 }; const client = new Client('my-store', 'key', options); ``` -------------------------------- ### Instantiate multiple clients Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/06-module-exports.md Create isolated client instances for different stores. ```typescript import { Client } from 'swell-node'; const client1 = new Client('store-1', 'key-1'); const client2 = new Client('store-2', 'key-2'); const products1 = await client1.get('/products'); const products2 = await client2.get('/products'); ``` -------------------------------- ### Import ClientOptions interface Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/06-module-exports.md Import the interface for client configuration options. ```typescript import { ClientOptions } from 'swell-node'; ``` -------------------------------- ### Create Multiple Clients Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/01-client-class.md Uses createClient to manage connections to multiple stores within the same process. ```typescript import { swell } from 'swell-node'; // Create multiple clients for different stores const store1 = swell.createClient('store-1', 'key-1'); const store2 = swell.createClient('store-2', 'key-2', { timeout: 15000, maxSockets: 50 }); const products1 = await store1.get('/products'); const products2 = await store2.get('/products'); ``` -------------------------------- ### Load Environment Configuration Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/10-authentication.md Use dotenv to manage environment-specific configuration files. ```text .env.development: SWELL_STORE_ID=dev-store SWELL_API_KEY=dev-key-xxx ``` ```text .env.production: SWELL_STORE_ID=prod-store SWELL_API_KEY=prod-key-yyy ``` ```typescript import 'dotenv/config'; const client = new Client( process.env.SWELL_STORE_ID, process.env.SWELL_API_KEY ); ``` -------------------------------- ### Configure Client for Reliable Networks with Monitoring Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/04-configuration.md Integrates request tracking and client lifecycle logging for production observability. ```typescript const client = new Client('my-store', 'key', { timeout: 10000, retries: 3, headers: { 'X-App': 'myapp' }, onRequestComplete: (stats) => { metrics.recordRequestDuration(stats.method, stats.url, stats.durationMs); if (!stats.success) { logger.warn(`Request failed: ${stats.url}`); } }, onClientRecycle: (stats) => { logger.info(`Client recycled: ${stats.totalRequests} requests`); } }); ``` -------------------------------- ### Client.get(url, data?, headers?) Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/00-index.md Retrieves resource(s) from the specified URL. ```APIDOC ## GET [url] ### Description Retrieves resource(s) from the specified URL. ### Method GET ### Parameters #### Path Parameters - **url** (string) - Required - The resource path to retrieve. #### Query Parameters - **data** (object) - Optional - Query parameters to include in the request. - **headers** (object) - Optional - Custom headers for the request. ``` -------------------------------- ### Bulk Create Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/05-usage-patterns.md Creates multiple resources in parallel. ```typescript const items = [ { name: 'Item 1', price: 10 }, { name: 'Item 2', price: 20 }, { name: 'Item 3', price: 30 } ]; const created = await Promise.all( items.map(item => client.post('/products', item)) ); console.log('Created', created.length, 'products'); ``` -------------------------------- ### Handle Missing API Key Initialization Error Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/03-errors.md Triggered when init() is called with an undefined, null, or empty clientKey. ```typescript client.init('my-store'); // Throws client.init('my-store', ''); // Throws if empty string client.init('my-store', null); // Throws ``` ```typescript const client = new Client(); try { client.init('my-store'); } catch (error) { console.log(error.message); // "Swell store 'key' is required to connect" } ``` -------------------------------- ### Configure client settings Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/00-index.md Customize client behavior such as timeouts, retries, and request monitoring using the Client constructor. ```typescript import { Client } from 'swell-node'; const client = new Client('my-store', 'secret-key', { timeout: 10000, retries: 3, maxSockets: 100, onRequestComplete: (stats) => { console.log(`${stats.method} ${stats.url}: ${stats.durationMs}ms`); } }); const products = await client.get('/products', { limit: 20 }); ``` -------------------------------- ### createClient(clientId, clientKey, options) Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/01-client-class.md A factory method to generate a new, independent Client instance, useful for managing multiple store connections within a single process. ```APIDOC ## createClient(clientId, clientKey, options) ### Description Creates a new initialized Client instance. This is a convenience method for connecting to multiple stores simultaneously. ### Parameters - **clientId** (string) - Required - Store ID for the new client. - **clientKey** (string) - Required - API key for the new client. - **options** (ClientOptions) - Optional - Configuration options for the new client. ### Returns - **Client** - A new initialized Client instance. ``` -------------------------------- ### Initialize and use the swell singleton Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/06-module-exports.md Initialize the singleton once at startup before performing API requests. ```typescript import { swell } from 'swell-node'; // Initialize once swell.init('my-store', 'secret-key'); // Use throughout application const products = await swell.get('/products'); const order = await swell.post('/orders', { items: [...] }); ``` -------------------------------- ### Run Test Suites Source: https://github.com/swellstores/swell-node/blob/master/copilot-instructions.md Commands for executing tests in the Swell Node project, including watch mode and pattern-based filtering. ```bash npm test # Run all tests npm run test:watch # Watch mode npm test -- --testNamePattern="recycling" # Specific tests ``` -------------------------------- ### Package.json Configuration Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/06-module-exports.md Configuration settings for the package distribution files. ```json { "main": "dist/index.js", "types": "dist/index.d.ts", "files": ["dist"] } ``` -------------------------------- ### Create an uninitialized client Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/08-api-client-lifecycle.md Instantiate the client without triggering immediate HTTP client creation. ```typescript const client = new Client(); // No HTTP client created yet console.log(client.httpClient); // null ``` -------------------------------- ### Configuring Swell Client for Production Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/05-usage-patterns.md Set production-grade timeouts, retries, and monitoring hooks to track request performance and client health. ```typescript const client = new Client('my-store', 'secret-key-from-env', { url: process.env.SWELL_API_URL || 'https://api.swell.store', timeout: 15000, retries: 3, maxSockets: 100, verifyCert: process.env.NODE_ENV === 'production', headers: { 'X-App': process.env.npm_package_name, 'X-App-Version': process.env.npm_package_version }, onRequestComplete: (stats) => { if (!stats.success || stats.durationMs > 5000) { logger.warn('Slow/failed request', { method: stats.method, url: stats.url, duration: stats.durationMs, success: stats.success, attempts: stats.attempts }); } }, onClientRecycle: (stats) => { logger.info('Client recycled', { totalRequests: stats.totalRequests, ageMs: stats.ageMs }); } }); ``` -------------------------------- ### Managing Environment Variables Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/05-usage-patterns.md Store sensitive credentials and configuration in environment files and parse them during client initialization. ```typescript // .env SWELL_STORE_ID=my-store SWELL_API_KEY=secret-key SWELL_API_URL=https://api.swell.store SWELL_TIMEOUT=15000 SWELL_RETRIES=3 // app.ts const client = new Client( process.env.SWELL_STORE_ID!, process.env.SWELL_API_KEY!, { timeout: parseInt(process.env.SWELL_TIMEOUT || '15000'), retries: parseInt(process.env.SWELL_RETRIES || '3') } ); ``` -------------------------------- ### Configure Client for Memory Management Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/08-api-client-lifecycle.md Implement aggressive recycling and monitoring to mitigate steady memory growth. ```typescript const client = new Client('my-store', 'key', { recycleAfterRequests: 500, // Recycle more frequently recycleAfterMs: 5000, // Recycle sooner keepAliveMs: 500, // Close sockets faster onClientRecycle: (stats) => { console.log('Client recycled'); } }); // Monitor cleanup setInterval(() => { const stats = client.getClientStats(); if (stats.oldClientsCount > 2) { console.warn('Old clients not cleaning up:', stats.oldClientsCount); } }, 5000); ``` -------------------------------- ### Initialize Client with Default HTTPS Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/10-authentication.md The default API URL uses HTTPS for secure communication. ```typescript const client = new Client('my-store', 'key'); // url: https://api.swell.store (secure) ``` -------------------------------- ### Uninitialized Client Error Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/03-errors.md Error thrown when attempting to perform API requests before the client has been initialized. ```APIDOC ## API Request Execution ### Description Attempting to call methods like `get()` on a client instance that has not been initialized via `init()` will result in an error. ### Error - **Swell API client not initialized**: Thrown when a request is made before calling `init()`. ``` -------------------------------- ### Mocking the Swell Client for Tests Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/05-usage-patterns.md Use a test store ID and key to initialize the client within test suites. ```typescript import { Client } from 'swell-node'; describe('My Service', () => { it('fetches products', async () => { const client = new Client('test-store', 'test-key'); // In tests, mock the HTTP layer or use test API const products = await client.get('/products'); expect(products).toBeDefined(); }); }); ``` -------------------------------- ### Configure Credentials via Environment Variables Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/10-authentication.md Set store credentials as environment variables before executing the Node.js application. ```bash # Start app with credentials in environment export SWELL_STORE_ID=my-store export SWELL_API_KEY=secret-key node app.js ``` -------------------------------- ### Configure Client for Resource-Constrained Environments Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/08-api-client-lifecycle.md Limits concurrent connections and shortens persistence to minimize memory footprint in serverless or embedded contexts. ```typescript const client = new Client('my-store', 'key', { maxSockets: 20, // Limit concurrent connections keepAliveMs: 500, // Short socket persistence recycleAfterRequests: 500, // More frequent recycling recycleAfterMs: 5000 }); ``` -------------------------------- ### Simple PUT Request Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/07-http-methods.md Updates a product resource with new name and price fields. ```typescript const updated = await client.put('/products/prod-123', { name: 'Updated Product Name', price: 39.99 }); console.log('Updated product:', updated); ``` -------------------------------- ### Manage Credentials with Docker Secrets Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/10-authentication.md Configure a Dockerfile and read secret files mounted at runtime. ```dockerfile # Dockerfile FROM node:16 WORKDIR /app COPY . . RUN npm install CMD ["node", "app.js"] # Run with Docker secrets # docker run --secret swell_key myimage ``` ```typescript // Load from Docker secrets file import fs from 'fs'; const apiKey = fs.readFileSync('/run/secrets/swell_key', 'utf-8'); const client = new Client('my-store', apiKey); ``` -------------------------------- ### Fetch all products with pagination Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/05-usage-patterns.md Iterates through all pages of a resource by manually managing the offset and limit parameters. ```typescript async function fetchAllProducts(client: Client) { const pageSize = 50; const allProducts = []; let offset = 0; let hasMore = true; while (hasMore) { const response = await client.get('/products', { limit: pageSize, offset: offset }); allProducts.push(...response.results); hasMore = response.count > offset + pageSize; offset += pageSize; } return allProducts; } ``` -------------------------------- ### Use Typed Responses with Client Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/00-index.md Demonstrates importing core types and using generics to enforce response structures. ```typescript import { Client, ClientOptions, HttpMethod, RequestStats } from 'swell-node'; // Typed responses interface Product { id: string; name: string; price: number; } const product = await client.get('/products/123'); console.log(product.name); // TypeScript knows about name ``` -------------------------------- ### Re-initialize Client Credentials Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/10-authentication.md Switch credentials for an existing client instance using the init method. ```typescript const client = new Client('store-1', 'key-1'); // Later, switch to different credentials client.init('store-2', 'key-2'); // Now requests are authenticated with store-2 credentials const products = await client.get('/products'); ``` -------------------------------- ### swell (Singleton) Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/06-module-exports.md A pre-instantiated, uninitialized singleton instance of the Client class. It is used for accessing the Swell API globally after calling init(). ```APIDOC ## swell (Singleton) ### Description A singleton instance of the Client class. Useful for accessing the Swell API from anywhere in your application after calling init() once. ### Usage ```typescript import { swell } from 'swell-node'; // Initialize once swell.init('my-store', 'secret-key'); // Use throughout application const products = await swell.get('/products'); ``` ``` -------------------------------- ### Axios configuration object Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/08-api-client-lifecycle.md The default configuration applied to the Axios instance during client initialization. ```javascript { baseURL: options.url, headers: { 'Content-Type': 'application/json', 'User-Agent': 'swell-node@6.0.5', 'Authorization': 'Basic ' }, httpAgent: HttpCookieAgent { cookies: CookieJar, keepAlive: true, maxSockets: 100, keepAliveMsecs: 1000 }, httpsAgent: HttpsCookieAgent { cookies: CookieJar, rejectUnauthorized: true, keepAlive: true, maxSockets: 100, keepAliveMsecs: 1000 }, timeout: 10000 } ``` -------------------------------- ### Configure Client for Temporary Network Issues Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/09-retry-logic.md Configures the client with a retry limit to handle transient connection refusals. ```typescript const client = new Client('my-store', 'key', { retries: 2 }); // First attempt: Connection refused // Wait 50ms // Second attempt: Connection refused // Wait 50ms // Third attempt: Succeeds! const products = await client.get('/products'); ``` -------------------------------- ### Perform API requests Source: https://github.com/swellstores/swell-node/blob/master/README.md Execute asynchronous requests to the Swell API using the initialized client. ```javascript try { const { data } = await swell.get('/products', { active: true }); console.log(data); } catch (err) { console.error(err.message); } ``` -------------------------------- ### Build and Lint Commands Source: https://github.com/swellstores/swell-node/blob/master/copilot-instructions.md Standard maintenance commands for compiling TypeScript, linting, and formatting the codebase. ```bash npm run build # TypeScript compilation to dist/ npm run lint # ESLint + Prettier npm run prettier # Format code ``` -------------------------------- ### Handle Missing Store ID Initialization Error Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/03-errors.md Triggered when init() is called with an undefined, null, or empty clientId. ```typescript client.init(undefined, 'key'); // Throws client.init('', 'key'); // Throws if empty string client.init(null, 'key'); // Throws ``` ```typescript const client = new Client(); try { client.init(undefined, 'key'); } catch (error) { console.log(error.message); // "Swell store 'id' is required to connect" } ``` -------------------------------- ### post(url, data, headers) Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/01-client-class.md Makes a POST HTTP request to the Swell API to create resources. ```APIDOC ## post(url, data, headers) ### Description Makes a POST HTTP request to the Swell API. ### Parameters - **url** (string) - Required - API endpoint path. - **data** (unknown) - Required - Request body data. - **headers** (HttpHeaders) - Optional - Additional HTTP headers. ``` -------------------------------- ### Use Environment-Specific Keys Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/10-authentication.md Maintain separate credentials for development and production environments. ```typescript // Development const devClient = new Client( process.env.DEV_SWELL_STORE_ID, process.env.DEV_SWELL_API_KEY ); // Production const prodClient = new Client( process.env.PROD_SWELL_STORE_ID, process.env.PROD_SWELL_API_KEY ); ``` -------------------------------- ### Configure Client for EMFILE Error Resolution Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/08-api-client-lifecycle.md Adjust socket limits and recycling frequency to prevent 'too many open files' errors. ```typescript const client = new Client('my-store', 'key', { maxSockets: 50, // Reduce concurrent sockets keepAliveMs: 500, // Close sockets faster recycleAfterRequests: 500 // Recycle more frequently }); ``` -------------------------------- ### Simple POST Request Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/07-http-methods.md Basic usage of the post method to create a new resource. ```typescript const newProduct = await client.post('/products', { name: 'New Product', price: 29.99, description: 'Product description' }); console.log('Created product ID:', newProduct.id); ``` -------------------------------- ### HTTP Basic Authentication Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/10-authentication.md Details on how to authenticate API requests using store credentials. ```APIDOC ## HTTP Basic Authentication ### Description All API requests must be authenticated using HTTP Basic Authentication. The credentials consist of a store ID and an API key, which must be base64 encoded. ### Method HTTP Basic Authentication ### Authentication Header `Authorization: Basic {base64(storeId:apiKey)}` ### Requirements - **storeId**: Required - **apiKey**: Required - **Protocol**: HTTPS (Required) ### Best Practices - Store credentials in environment variables. - Rotate API keys regularly. - Use minimal scopes for API keys. - Monitor API usage. ``` -------------------------------- ### Importing Available Exports Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/06-module-exports.md Lists the primary classes, enums, and interfaces available for import from the swell-node package. ```typescript import { // Singleton swell, // Classes Client, // Enums HttpMethod, // Interfaces HttpHeaders, HttpClientWrapper, RequestStats, ClientOptions } from 'swell-node'; ``` -------------------------------- ### Handle 404 Not Found Source: https://github.com/swellstores/swell-node/blob/master/_autodocs/03-errors.md Catch errors when the requested resource does not exist. ```typescript try { await client.get('/products/nonexistent-id'); } catch (error) { if ((error as any).status === 404) { console.log('Product not found'); } } ```