### Basic Setup and API Calls Source: https://github.com/swellstores/apps-sdk/blob/master/README.md Demonstrates how to initialize the Swell SDK and make basic backend and storefront API calls. ```APIDOC ## Basic Setup ### Description Initializes the Swell SDK and demonstrates making calls to both the backend and storefront APIs. ### Method `POST` ### Endpoint `/api/example` ### Request Body ```typescript import { Swell } from '@swell/apps-sdk'; // Initialize Swell instance in your app frontend const swell = new Swell({ serverHeaders: context.request.headers, // Headers from worker environment }); // Make backend API calls const products = await swell.backend.get('/products'); // Make storefront API calls const cart = await swell.storefront.get('/cart'); ``` ### Response #### Success Response (200) - **products** (Array) - Response from the backend `/products` endpoint. - **cart** (Object) - Response from the storefront `/cart` endpoint. #### Response Example ```json { "products": [ // ... product data ], "cart": { // ... cart data } } ``` ``` -------------------------------- ### Building and Watching the SDK - Bash Source: https://github.com/swellstores/apps-sdk/blob/master/README.md Commands for building the Swell Apps SDK for production and for watching for changes during development. Includes installing dependencies, running the build command, and initiating the watch process. ```bash # Install dependencies npm install # Build for production npm run build # Watch for changes npm run watch # Run tests npm test ``` -------------------------------- ### Install Swell Apps SDK using npm Source: https://github.com/swellstores/apps-sdk/blob/master/README.md This command installs the Swell Apps SDK package from npm, making it available for use in your project. Ensure you have Node.js and npm installed. ```bash npm install @swell/apps-sdk ``` -------------------------------- ### Memory Caching with Custom Handler - TypeScript Source: https://github.com/swellstores/apps-sdk/blob/master/README.md Example of utilizing Swell's in-memory caching mechanism. The `getCachedResource` function allows you to cache the results of an expensive operation, providing a fallback function to perform the operation if the data is not found in the cache. ```typescript // Cached resource with custom handler const cachedData = await swell.getCachedResource( 'expensive-operation', [param1, param2], async () => { return await performExpensiveOperation(param1, param2); } ); ``` -------------------------------- ### Initialize Swell Theme and Render Page (TypeScript) Source: https://github.com/swellstores/apps-sdk/blob/master/README.md Illustrates initializing the SwellTheme with custom configurations and rendering a theme page. This involves fetching settings, preparing page data with deferred resource loading, and rendering the output. ```typescript import { Swell, SwellTheme, SwellProduct } from '@swell/apps-sdk'; const swell = new Swell({ serverHeaders: context.request.headers, ...options, }); // Initialize theme with optional configuration const theme = new SwellTheme(swell, { forms: formConfigs, resources: customResources, globals: additionalGlobals, }); // Fetch settings and set global context await theme.initGlobals('product'); // page ID // Create page data with deferred resource loading const data = { product: new SwellProduct(swell, context.params.id), }; // Render theme page const renderedPage = await theme.renderPage(data); ``` -------------------------------- ### Initialize Swell SDK and Make API Calls (TypeScript) Source: https://github.com/swellstores/apps-sdk/blob/master/README.md Demonstrates how to initialize the Swell SDK instance and make basic backend and storefront API calls. It requires the 'context.request.headers' for initialization. ```typescript import { Swell } from '@swell/apps-sdk'; // Initialize Swell instance in your app frontend const swell = new Swell({ serverHeaders: context.request.headers, // Headers from worker environment }); // Make backend API calls const products = await swell.backend.get('/products'); // Make storefront API calls const cart = await swell.storefront.get('/cart'); ``` -------------------------------- ### Theme Rendering Source: https://github.com/swellstores/apps-sdk/blob/master/README.md Illustrates how to initialize and use the `SwellTheme` class for rendering theme pages with dynamic data and deferred resource loading. ```APIDOC ## Theme Rendering ### Description Shows how to initialize a `SwellTheme` instance, fetch settings, prepare page data with deferred loading, and render a theme page. ### Method `GET` ### Endpoint `/products/:id` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the product to fetch. ### Request Body ```typescript import { Swell, SwellTheme, SwellProduct } from '@swell/apps-sdk'; const swell = new Swell({ serverHeaders: context.request.headers, ...options, }); // Initialize theme with optional configuration const theme = new SwellTheme(swell, { forms: formConfigs, resources: customResources, globals: additionalGlobals, }); // Fetch settings and set global context await theme.initGlobals('product'); // page ID // Create page data with deferred resource loading const data = { product: new SwellProduct(swell, context.params.id), }; // Render theme page const renderedPage = await theme.renderPage(data); ``` ### Response #### Success Response (200) - **renderedPage** (string) - The HTML content of the rendered theme page. ``` -------------------------------- ### Headers and App Proxying Source: https://github.com/swellstores/apps-sdk/blob/master/README.md Explains the importance of proxy-injected headers for SDK functionality and how to pass them during initialization. ```APIDOC ## Headers and App Proxying ### Description Details the essential headers provided by Swell's proxy infrastructure and how to pass them to the `Swell` constructor for proper SDK operation. ### Method `GET` ### Endpoint `/` ### Request Body ```typescript import { Swell } from '@swell/apps-sdk'; // Headers passed from Swell's proxy contain: // - swell-store-id: The store identifier // - swell-public-key: Frontend API access key // - swell-access-token: Backend API access token (scoped to app permissions) // - swell-storefront-id: Current storefront instance // - swell-environment-id: Environment (development, staging, production) // - swell-theme-id: Active theme identifier // - swell-storefront-context: Preloaded cart/account data const swell = new Swell({ serverHeaders: context.request.headers, // Contains all proxy-injected headers getCookie: (name) => getCookieValue(name), setCookie: (name, value, options) => setCookieValue(name, value, options), }); // Without these headers, the SDK cannot: // - Authenticate with Swell APIs // - Determine which store and storefront to operate on // - Access cached resources or maintain session state // - Render themes with proper configuration // The `serverHeaders` parameter should always be passed the complete headers object // from your app's request context to ensure full functionality. ``` ### Response #### Success Response (200) - **Initialization Status** (string) - Indicates successful initialization of the Swell SDK with provided headers. ``` -------------------------------- ### Configure Swell SDK with Proxy Headers and Cookies (TypeScript) Source: https://github.com/swellstores/apps-sdk/blob/master/README.md Shows how to initialize the Swell SDK with necessary proxy headers and cookie handling functions. This is crucial for authentication and session management in a deployed Swell app. ```typescript // Headers passed from Swell's proxy contain: // - swell-store-id: The store identifier // - swell-public-key: Frontend API access key // - swell-access-token: Backend API access token (scoped to app permissions) // - swell-storefront-id: Current storefront instance // - swell-environment-id: Environment (development, staging, production) // - swell-theme-id: Active theme identifier // - swell-storefront-context: Preloaded cart/account data const swell = new Swell({ serverHeaders: context.request.headers, // Contains all proxy-injected headers getCookie: (name) => getCookieValue(name), setCookie: (name, value, options) => setCookieValue(name, value, options), }); ``` -------------------------------- ### Swell Initialization with Cloudflare KV Caching - TypeScript Source: https://github.com/swellstores/apps-sdk/blob/master/README.md Configuration snippet for initializing the Swell SDK with Cloudflare KV caching enabled. This requires providing the necessary server headers, worker environment variables (containing the THEME KV binding), and the worker context. ```typescript const swell = new Swell({ serverHeaders: context.request.headers, workerEnv: context.locals.runtime.env, // Contains THEME KV binding workerCtx: context.locals.runtime.ctx, // Worker context }); ``` -------------------------------- ### Swell Class API Source: https://github.com/swellstores/apps-sdk/blob/master/README.md The Swell class is the primary entry point for interacting with the Swell Apps SDK, offering access to backend and storefront APIs, configuration options, and state management. ```APIDOC ## Swell Class ### Description The main entry point for SDK functionality, providing access to API clients, configuration, and state management. ### Class `Swell` ### Properties - **backend** (`SwellBackendAPI`) - Access to the Swell Backend API. - **storefront** (`typeof SwellJS`) - Access to the Swell Storefront API. - **config** (`SwellAppConfig`) - Configuration object for the Swell app. - **url** (`URL`) - The URL of the current request. - **headers** (`Record`) - Request headers. - **queryParams** (`ParsedQs`) - Parsed query parameters from the request URL. - **isEditor** (`boolean`) - Flag indicating if the app is running in the editor. - **isPreview** (`boolean`) - Flag indicating if the app is running in preview mode. - **storefrontContext** (`SwellData`) - Contextual data from the storefront. ### Methods - **get**``(`url: string`, `query?: SwellData`): `Promise` - Makes a GET request to the specified URL. - **post**``(`url: string`, `data: SwellData`): `Promise` - Makes a POST request with the given data. - **put**``(`url: string`, `data: SwellData`): `Promise` - Makes a PUT request with the given data. - **delete**``(`url: string`, `data?: SwellData`): `Promise` - Makes a DELETE request. - **getCachedResource**``(`key: string`, `args: unknown[]`, `handler: () => T`, `isCacheble = true`): `Promise` - Retrieves a resource from the cache or fetches it using the provided handler. ``` -------------------------------- ### Lazy Loading Resources in Liquid Templates - Liquid Source: https://github.com/swellstores/apps-sdk/blob/master/README.md Illustrates lazy loading of resources within Liquid templates. Product data and collection items are only fetched when they are actually accessed in the template, improving performance by deferring network requests. ```liquid {{ product.name }} {% for item in collection.products %} {{ item.name }} {% endfor %} ``` -------------------------------- ### Swell Class API Reference (TypeScript) Source: https://github.com/swellstores/apps-sdk/blob/master/README.md Provides a reference for the main Swell class, detailing its properties for API access, configuration, and state management, as well as available methods for data retrieval and manipulation. ```typescript class Swell { // API access backend: SwellBackendAPI; storefront: typeof SwellJS; // Configuration config: SwellAppConfig; url: URL; headers: Record; queryParams: ParsedQs; // State isEditor: boolean; isPreview: boolean; storefrontContext: SwellData; // Methods get(url: string, query?: SwellData): Promise; post(url: string, data: SwellData): Promise; put(url: string, data: SwellData): Promise; delete(url: string, data?: SwellData): Promise; getCachedResource(key: string, args: unknown[], handler: () => T, isCacheble = true): Promise; } ``` -------------------------------- ### Custom Resource Class and Usage - TypeScript Source: https://github.com/swellstores/apps-sdk/blob/master/README.md This snippet demonstrates how to create a custom storefront resource class by extending `SwellStorefrontCollection` and how to use it within theme data. This allows for custom collection handling with specific query parameters. ```typescript // Create custom resource class class MyAppCollection extends SwellStorefrontCollection { constructor(swell: Swell, query: SwellData = {}) { super(swell, 'my-app-collection', query); return this._getProxy(); } } // Usage in theme data const data = { myCollection: new MyAppCollection(swell, { limit: 20 }), }; ``` -------------------------------- ### SwellTheme Class for Theme Rendering - TypeScript Source: https://github.com/swellstores/apps-sdk/blob/master/README.md The SwellTheme class is responsible for managing and rendering themes. It provides methods to initialize global theme settings, render pages, sections, and layouts, retrieve section schemas, and set global variables. It utilizes Swell, ThemeGlobals, and LiquidSwell for its operations. ```typescript class SwellTheme { // Core properties swell: Swell; globals: ThemeGlobals; liquidSwell: LiquidSwell; // Methods initGlobals(pageId: string, altTemplate?: string): Promise; renderPage(pageData?: SwellData, altTemplate?: string): Promise; renderSection(sectionId: string, pageData?: SwellData): Promise; renderLayout(layoutName?: string, data?: SwellData): Promise; getSectionSchema(sectionName: string): Promise; setGlobals(globals: Partial): void; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.