### Install dc-delivery-sdk-js with npm Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Install the SDK using npm for use in your project. ```sh npm install dc-delivery-sdk-js --save ``` -------------------------------- ### Get All Delivery Keys Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ContentModels.md Example showing how to retrieve all delivery keys for a content item, including the primary delivery key and any additional keys. ```typescript const keys = [ item.body._meta.deliveryKey, ...(item.body._meta.deliveryKeys?.values?.map(v => v.value) || []) ]; ``` -------------------------------- ### Localized Content Example (All Locales) Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Example of a JSON response for content with field-level localization, showing values for multiple locales. ```json { "_meta": { "schema": "https://www.anyafinn.online/content-types/slide.json", "deliveryId": "d6ccc158-6ab7-48d0-aa85-d9fbf2aef000", "name": "example-slide" }, "heading": { "_meta": { "schema": "http://bigcontent.io/cms/schema/v1/core#/definitions/localized-value" }, "values": [ { "locale": "en-US", "value": "Free shipping until Sunday!" }, { "locale": "de-de", "value": "Kostenloser Versand bis Sonntag!" } ] } } ``` -------------------------------- ### Complete Example: Preview Content at Snapshot Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/StagingEnvironmentFactory.md Demonstrates generating a pinned staging domain for a specific snapshot and then using it with ContentClient to fetch content. ```typescript import { ContentClient, StagingEnvironmentFactory } from 'dc-delivery-sdk-js'; async function previewContentAtSnapshot( snapshotId: string, contentItemId: string ) { // Generate pinned domain const factory = new StagingEnvironmentFactory( 'fhboh562c3tx1844c2ycknz96.staging.bigcontent.io' ); const stagingEnvironment = await factory.generateDomain({ snapshotId: snapshotId }); // Create client pointing to pinned staging environment const client = new ContentClient({ account: 'myaccount', stagingEnvironment: stagingEnvironment }); // Fetch content from the pinned snapshot const content = await client.getContentItemById(contentItemId); console.log(content.body); } ``` -------------------------------- ### Localized Content Example (Single Locale) Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Example of a JSON response after configuring the ContentClient with a locale query, showing only the value for the matched locale. ```json { "_meta": { "schema": "https://www.anyafinn.online/content-types/slide.json", "deliveryId": "d6ccc158-6ab7-48d0-aa85-d9fbf2aef000", "name": "example-slide" }, "heading": "Free shipping until Sunday!" } ``` -------------------------------- ### Complete Example: Preview Content at Timestamp Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/StagingEnvironmentFactory.md Demonstrates generating a pinned staging domain for a specific timestamp and using it with ContentClient, including a preview key, to fetch content. ```typescript async function previewContentAtTimestamp( timestamp: number, contentItemId: string ) { const factory = new StagingEnvironmentFactory( 'fhboh562c3tx1844c2ycknz96.staging.bigcontent.io' ); const stagingEnvironment = await factory.generateDomain({ timestamp: timestamp }); const client = new ContentClient({ account: 'myaccount', stagingEnvironment: stagingEnvironment, previewKey: 'amp_vse_XXXXXX.XXXXXXXXXXXX==' }); const content = await client.getContentItemById(contentItemId); return content; } ``` -------------------------------- ### Check Edition Status Example Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ContentModels.md Compares the current date with the edition's start and end dates to determine its status. Requires fetching content item first. ```typescript const item = await client.getContentItemById('id'); const edition = item.body._meta.edition; if (edition) { const now = new Date(); const start = edition.getStartDate(); const end = edition.getEndDate(); if (now < start) { console.log('Content is scheduled for the future'); } else if (now > end) { console.log('Edition has ended'); } else { console.log('Edition is currently active'); } } ``` -------------------------------- ### Example: Fetching First and Next Pages Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/FilterBy.md Demonstrates how to fetch the first page of results and then subsequent pages using the cursor from the previous response. Ensure the content type is specified before pagination. ```typescript const page1 = await client .filterByContentType('https://example.com/blog-post.json') .page(10) .request(); const page2 = await client .filterByContentType('https://example.com/blog-post.json') .page(10, page1.page.nextCursor) .request(); ``` -------------------------------- ### Complete Error Handling Example Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/errors.md A comprehensive example demonstrating robust error handling for the ContentClient. It imports necessary classes and uses a try-catch block to handle specific errors like ContentNotFoundError, HttpError (with various status codes), NotSupportedV2Error, and ETIMEDOUT. ```typescript import { ContentClient, ContentNotFoundError, HttpError } from 'dc-delivery-sdk-js'; async function fetchContent(contentId) { const client = new ContentClient({ hubName: 'myhub', timeout: 5000 }); try { const content = await client.getContentItemById(contentId); return content; } catch (error) { // Handle specific errors if (error instanceof ContentNotFoundError) { console.error(`Content "${error.contentItem}" not found`); return null; } if (error instanceof HttpError) { switch (error.status) { case 401: console.error('Authentication failed - check API key'); break; case 404: console.error('Endpoint not found'); break; case 429: console.error('Rate limited - retry after delay'); break; case 500: console.error('Server error - please try again'); break; default: console.error(`HTTP error ${error.status}: ${error.message}`); } return null; } if (error.name === 'NOT_SUPPORTED_V2') { console.error('This method requires hubName configuration'); return null; } if (error.code === 'ETIMEDOUT') { console.error('Request timed out - increase timeout or retry'); return null; } // Unknown error console.error('Unexpected error:', error.message); throw error; } } ``` -------------------------------- ### Success Response Example Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/MultiFetchPatterns.md Illustrates the structure of a successful content item response, including content fields and metadata. ```typescript { content: { // Schema-defined fields title: 'Article Title', author: 'Author Name', // Plus _meta _meta: { deliveryId: 'id', name: 'article name', schema: 'https://...' } }, linkedContent?: [ // Linked content items (if any) ] } ``` -------------------------------- ### Example JSON Response Structure Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md This is an example of the JSON structure returned when fetching content that may include linked items, such as a carousel with slides. The '_meta' property contains standard metadata. ```json { "_meta": { "schema": "https://www.anyafinn.online/content-types/carousel.json", "deliveryId": "543246b7-5948-4849-884c-b295402a95b4", "name": "example-carousel" }, "slides": [ { "_meta": { "schema": "https://www.anyafinn.online/content-types/slide.json", "deliveryId": "d6ccc158-6ab7-48d0-aa85-d9fbf2aef000", "name": "example-slide" }, "heading": "Free shipping until Sunday!" } ] } ``` -------------------------------- ### Example: Requesting Filtered and Paginated Content Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/FilterBy.md Shows how to apply content type filters, category filters, sorting, pagination, and request options like depth, format, and locale. It also demonstrates how to access response counts and fetch the next page. ```typescript const response = await client .filterByContentType('https://example.com/blog-post.json') .filterBy('/category', 'Technology') .sortBy('date', 'DESC') .page(10) .request({ depth: 'all', format: 'inlined', locale: 'en-US' }); console.log(`Found ${response.page.responseCount} items`); response.responses.forEach(item => { console.log(item.content._meta.name); }); // Fetch next page if available if (response.page.next) { const nextPage = await response.page.next(); } ``` -------------------------------- ### Example: Catching ETIMEDOUT Error Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/errors.md Shows how to catch an ETIMEDOUT error, which is thrown when a request exceeds the configured timeout. The example checks the error code and suggests retrying or increasing the timeout. ```typescript try { const content = await client.getContentItemById('item-id'); } catch (error) { if (error.code === 'ETIMEDOUT') { console.log('Request timed out'); // Retry or increase timeout } } ``` -------------------------------- ### Identify Content Type Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ContentModels.md Example demonstrating how to identify the content type of an item by checking its schema property within ContentMeta. ```typescript const contentType = item.body._meta.schema; if (contentType === 'https://example.com/blog-post.json') { // Handle blog post } ``` -------------------------------- ### Example: Catching NotSupportedV2Error Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/errors.md Demonstrates how to catch a NotSupportedV2Error when calling `getContentItemByKey` without the `hubName` in the client configuration. It checks the error name and logs a specific message. ```typescript // Configuration only has account, not hubName const client = new ContentClient({ account: 'myaccount' }); try { const content = await client.getContentItemByKey('my-key'); } catch (error) { if (error.name === 'NOT_SUPPORTED_V2') { console.log('getContentItemByKey() requires hubName configuration'); } } ``` -------------------------------- ### Error Response Example Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/MultiFetchPatterns.md Shows the structure of an error response when a content item cannot be found. ```typescript { error: ContentNotFoundError { name: 'CONTENT_NOT_FOUND', contentItem: 'requested-id-or-key', message: 'Content item "..." was not found' } } ``` -------------------------------- ### Fixing Invalid Staging Environment Error Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/errors.md Demonstrates the incorrect use of `stagingEnvironment` by providing a full URL. The corrected example shows how to provide only the hostname, as required by the SDK. ```typescript // Wrong const client = new ContentClient({ account: 'myaccount', stagingEnvironment: 'https://abc123.staging.bigcontent.io' }); // Correct const client = new ContentClient({ account: 'myaccount', stagingEnvironment: 'abc123.staging.bigcontent.io' }); ``` -------------------------------- ### Detect Content Type for Rendering Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Use the _meta.schema property to determine the content type and select the appropriate React component for rendering. This example shows a switch statement to map schemas to components. ```json { "_meta": { "schema": "https://www.anyafinn.online/content-types/slot.json", "deliveryId": "62ece7d6-b541-411c-b776-0a6704ede1fb", "name": "homepage-hero" }, "slotContent": { "_meta": { "schema": "https://www.anyafinn.online/content-types/banner.json", "deliveryId": "28583572-c964-4755-825b-044718312a29", "name": "example-banner" }, "heading": "Free shipping until Sunday!" } } ``` ```javascript import React from 'react'; import { Banner, Carousel, Empty } from './components'; class App extends React.Component { //... getComponentForContentType(contentItem) { switch (contentItem._meta.schema) { case 'https://www.anyafinn.online/content-types/banner.json': return Banner; case 'https://www.anyafinn.online/content-types/carousel.json': return Carousel; default: return Empty; } } render() { const slotContent = this.props.content.slotContent; const TagName = this.getComponentForContentType(slotContent); return ; } } ``` -------------------------------- ### Example Content Item JSON Structure Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md This JSON represents the structure of a content item or slot fetched by its delivery key. It includes metadata like schema, delivery ID, and delivery key, along with content-specific fields and nested content. ```json { "_meta": { "schema": "https://www.anyafinn.online/content-types/carousel.json", "deliveryId": "543246b7-5948-4849-884c-b295402a95b4", "deliveryKey": "homepage-banner-slot", "name": "example-carousel" }, "slides": [ { "_meta": { "schema": "https://www.anyafinn.online/content-types/slide.json", "deliveryId": "d6ccc158-6ab7-48d0-aa85-d9fbf2aef000", "name": "example-slide" }, "heading": "Free shipping until Sunday!" } ] } ``` -------------------------------- ### Get Content Hierarchy Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/README.md Fetches the hierarchical structure of content starting from a specified root ID. Includes a utility function to print the hierarchy tree. ```typescript const hierarchy = await client.getByHierarchy({ rootId: 'root-item-id' }); function printTree(item, indent = 0) { console.log(' '.repeat(indent) + item.content._meta.name); item.children.forEach(child => printTree(child, indent + 2)); } printTree(hierarchy); ``` -------------------------------- ### Initialize Client with Preview Key for VSE Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Configures the ContentClient for a staging environment using a preview key for authentication. Ensure the stagingEnvironment is also set. ```javascript const client = new ContentClient({ account: 'myaccount', stagingEnvironment: 'fhboh562c3tx1844c2ycknz96.staging.bigcontent.io', previewKey: 'amp_vse_XXXXXXXXXXXXXX.XXXXXXXXXXXXXXXXXXXX==' }); ``` -------------------------------- ### Configure Media with Staging Environment Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/Media.md Shows how to configure the ContentClient to use a specific staging environment for media delivery. This is useful for previewing content before it goes live. ```typescript // Client configured with staging environment const client = new ContentClient({ account: 'myaccount', stagingEnvironment: 'preview.staging.bigcontent.io' }); const content = await client.getContentItemById('item-id'); // Media URLs will use the staging host const url = content.body.image.url().build(); // https://preview.staging.bigcontent.io/i/account/image ``` -------------------------------- ### Initialize ContentClient Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/overview.md Instantiate the main client for fetching content. Requires hub name for configuration. ```typescript const client = new ContentClient({ hubName: 'myhub' }); ``` -------------------------------- ### Initialize Client with Signing Proxy for VSE Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Sets up the ContentClient to use a signing proxy for authenticated requests to a staging environment. Both signingProxyAddress and stagingEnvironment must be provided. ```javascript const client = new ContentClient({ account: 'myaccount', stagingEnvironment: 'fhboh562c3tx1844c2ycknz96.staging.bigcontent.io', signingProxyAddress: "https//proxy.bigcontent.io" }); ``` -------------------------------- ### Example: Catching ECONNREFUSED Error Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/errors.md Provides an example of how to catch an ECONNREFUSED error, which occurs when the SDK cannot connect to the API endpoint. It checks the error code and logs a connection error message. ```typescript try { const content = await client.getContentItemById('item-id'); } catch (error) { if (error.code === 'ECONNREFUSED') { console.log('Unable to connect to API endpoint'); } } ``` -------------------------------- ### Generate Staging Domain and Initialize Client Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/overview.md Use StagingEnvironmentFactory to create a preview domain and then initialize a ContentClient configured for that staging environment. ```typescript const factory = new StagingEnvironmentFactory( 'abc123.staging.bigcontent.io' ); const domain = await factory.generateDomain({ snapshotId: 'snapshot-id' }); const client = new ContentClient({ account: 'test', stagingEnvironment: domain }); ``` -------------------------------- ### Configure Media with Custom Host Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/Media.md Demonstrates how to configure the ContentClient with a custom media host for serving assets. Image URLs generated will use this specified host. ```typescript // Client configured with custom media host const client = new ContentClient({ hubName: 'myhub', mediaHost: 'cdn.mybrand.com' }); const content = await client.getContentItemById('item-id'); // Image URLs will use the custom host const url = content.body.image.url().build(); // https://cdn.mybrand.com/i/account/image ``` -------------------------------- ### Initialize Client for Staging Environment Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Initializes the ContentClient to request content from a virtual staging environment (VSE). Requires account and stagingEnvironment configuration. ```javascript const client = new ContentClient({ account: 'myaccount', stagingEnvironment: 'fhboh562c3tx1844c2ycknz96.staging.bigcontent.io', }); ``` -------------------------------- ### Get Content Item (Deprecated) Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ContentClient.md The getContentItem method is deprecated and should be replaced with getContentItemById. ```typescript getContentItem(contentItemId: string): Promise> ``` -------------------------------- ### Hierarchy Response Structure Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Example of the reconstructed content tree response from the delivery service when fetching hierarchies. ```json { "content": { "_meta": { "name": "Root", "schema": "https://hierarchies.com", "hierarchy": { "root": true }, "deliveryId": "90d6fa96-6ce0-4332-b995-4e6c50b1e233" }, "propertyName1": "Root" }, "children": [ { "content": { "_meta": { "name": "A", "schema": "https://hierarchies.com", "hierarchy": { "parentId": "90d6fa96-6ce0-4332-b995-4e6c50b1e233", "root": false }, "deliveryId": "1ebab07d-acd8-4e19-a614-ec632cdf95d5" }, "propertyName1": "A" }, "children": [ { "content": { "_meta": { "name": "B", "schema": "https://hierarchies.com", "hierarchy": { "parentId": "1ebab07d-acd8-4e19-a614-ad8a-583ebf6efc80", "root": false }, "deliveryId": "4db37251-0c86-4f45-ad8a-583ebf6efc80" }, "propertyName1": "B" }, "children": [] }, { "content": { "_meta": { "name": "C", "schema": "https://hierarchies.com", "hierarchy": { "parentId": "1ebab07d-acd8-4e19-a614-ec632cdf95d5", "root": false }, "deliveryId": "68676cda-5ab2-4a5e-bcfb-58c5cf3eb8ed" }, "propertyName1": "C" }, "children": [] } ] } ] } ``` -------------------------------- ### Edition Class Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ContentModels.md Represents a scheduled edition publication, providing methods to access its start and end dates. ```APIDOC ## Edition Class Represents a scheduled edition publication. ### Properties | Property | Type | Description | |----------|------|-------------| | id | string | Unique edition ID | | start | string | ISO 8601 start date (when edition goes live) | | end | string | ISO 8601 end date (when edition ends) | ### Methods #### getStartDate Returns the edition start date as a JavaScript Date object. | Return Type | Description | |------------|-------------| | Date | Start date | #### getEndDate Returns the edition end date as a JavaScript Date object. | Return Type | Description | |------------|-------------| | Date | End date | **Example:** ```typescript const item = await client.getContentItemById('id'); const edition = item.body._meta.edition; if (edition) { const now = new Date(); const start = edition.getStartDate(); const end = edition.getEndDate(); if (now < start) { console.log('Content is scheduled for the future'); } else if (now > end) { console.log('Edition has ended'); } else { console.log('Edition is currently active'); } } ``` ``` -------------------------------- ### Check if Content is Expired Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ContentModels.md Example demonstrating how to check if content has expired using the lifecycle information within ContentMeta. ```typescript const item = await client.getContentItemById('id'); if (item.body._meta.lifecycle?.isExpired()) { console.log('Content has expired'); } ``` -------------------------------- ### Constructor Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ContentClient.md Creates a new ContentClient instance with the provided configuration. The configuration must include either an `account` for v1 API or `hubName` for v2/Fresh API. ```APIDOC ## Constructor ContentClient ### Description Creates a new ContentClient instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **config** (ContentClientConfigOptions) - Required - Client configuration with either `account` (v1) or `hubName` (v2) ### Throws - `TypeError` if config is missing or neither `account` nor `hubName` is provided - `TypeError` if `stagingEnvironment` contains a protocol (should be hostname only) ### Example ```typescript import { ContentClient } from 'dc-delivery-sdk-js'; // Content Delivery 2 API const client = new ContentClient({ hubName: 'myhub' }); // Content Delivery 1 API const client = new ContentClient({ account: 'myaccount' }); // Fresh API const client = new ContentClient({ hubName: 'myhub', apiKey: 'my-api-key' }); ``` ``` -------------------------------- ### Instantiate Video from Content Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/Media.md Videos are typically returned from content responses. This snippet shows how to access a Video instance from a content body. ```typescript const content = await client.getContentItemById('item-id'); const video = content.body.videoField; // Video instance ``` -------------------------------- ### Initialize ContentClient from global UMD bundle Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Initialize the ContentClient when using the pre-bundled UMD version directly included via a script tag. ```js const client = new ampDynamicContent.ContentClient({ hubName: 'myhub', }); ``` -------------------------------- ### Timeout Configuration Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/configuration.md Configure request timeouts for the ContentClient. A value of 0 disables the timeout. The example shows a 5-second timeout. ```typescript import { ContentClient } from 'dc-delivery-sdk-js'; // 5 second timeout const client = new ContentClient({ hubName: 'myhub', timeout: 5000 }); // No timeout const client = new ContentClient({ hubName: 'myhub', timeout: 0 }); ``` -------------------------------- ### build Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ImageUrlBuilder.md Returns the fully constructed URL with all transformations applied. ```APIDOC ## build ### Description Returns the fully constructed URL with all transformations applied. ### Method build ### Return Type - **string** - Complete transformed image URL ### Example ```typescript const url = image.url() .width(500) .height(500) .quality(85) .format(ImageFormat.WEBP) .build(); console.log(url); // https://images.example.com/i/account/image.webp?w=500&h=500&qlt=85 ``` ``` -------------------------------- ### Generate Virtual Staging Domain and Initialize ContentClient Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/README.md Use StagingEnvironmentFactory to generate a virtual staging domain, then initialize ContentClient with staging environment details and a preview key for accessing staging content. ```typescript const factory = new StagingEnvironmentFactory( 'abc123.staging.bigcontent.io' ); const domain = await factory.generateDomain({ snapshotId: 'snapshot-123' }); const client = new ContentClient({ account: 'test', stagingEnvironment: domain, previewKey: 'api-key' }); ``` -------------------------------- ### Hierarchy Root Check Example Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ContentModels.md Checks if a content item is the root of a hierarchy or retrieves its parent ID. Accesses hierarchy metadata from the content item. ```typescript const item = await client.getContentItemById('id'); const hierarchy = item.body._meta.hierarchy; if (hierarchy?.root) { console.log('This is a root hierarchy item'); } else if (hierarchy?.parentId) { console.log(`Parent ID: ${hierarchy.parentId}`); } ``` -------------------------------- ### Check Content Expiry Status Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ContentModels.md Provides examples of using the isExpired method to check if content has expired, both for the current time and a specific past date. ```typescript const lifecycle = item.body._meta.lifecycle; // Check if expired now if (lifecycle?.isExpired()) { // Don't display content } // Check if expired at a specific date const pastDate = new Date('2025-01-01'); if (lifecycle?.isExpired(pastDate)) { // Was expired on that date } ``` -------------------------------- ### Instantiate ContentClient Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ContentClient.md Create a new ContentClient instance with configuration options. Supports Content Delivery 2 API (hubName), Content Delivery 1 API (account), or Fresh API (hubName, apiKey). ```typescript import { ContentClient } from 'dc-delivery-sdk-js'; // Content Delivery 2 API const client = new ContentClient({ hubName: 'myhub' }); // Content Delivery 1 API const client = new ContentClient({ account: 'myaccount' }); // Fresh API const client = new ContentClient({ hubName: 'myhub', apiKey: 'my-api-key' }); ``` -------------------------------- ### Serialize ContentItem to JSON Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ContentModels.md Example demonstrating how to serialize a ContentItem to plain JSON using the toJSON() method, making it suitable for API responses or storage. ```typescript const content = await client.getContentItemById('item-id'); const json = content.toJSON(); // Safe to send to client or store as JSON ``` -------------------------------- ### Initialize ContentClient with ES6 imports Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Initialize the ContentClient using ES6 import syntax. Ensure your project supports ES6 modules. ```js import { ContentClient } from 'dc-delivery-sdk-js'; const client = new ContentClient({ hubName: 'myhub', }); ``` -------------------------------- ### Initialize ContentClient with CommonJS imports Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Initialize the ContentClient using CommonJS require syntax. Suitable for Node.js environments. ```js const ContentClient = require('dc-delivery-sdk-js').ContentClient; const client = new ContentClient({ hubName: 'myhub', }); ``` -------------------------------- ### Fixing Missing Configuration Error Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/errors.md Illustrates the incorrect way to create a ContentClient without any configuration, leading to a TypeError. It then shows the correct way by providing a configuration object with at least `hubName`. ```typescript // Wrong const client = new ContentClient(); // Correct const client = new ContentClient({ hubName: 'myhub' }); ``` -------------------------------- ### Fetch Content Hierarchy and Print Tree Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/overview.md Fetches a hierarchical content structure starting from a root ID and includes a recursive function to print the names of items in the tree. ```typescript const hierarchy = await client.getByHierarchy({ rootId: 'root-id' }); function printTree(item) { console.log(item.content._meta.name); item.children.forEach(printTree); } printTree(hierarchy); ``` -------------------------------- ### Basic Content Fetch by ID Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/configuration.md Initialize the client with an account name to fetch content by its ID. ```typescript import { ContentClient } from 'dc-delivery-sdk-js'; const client = new ContentClient({ account: 'myaccount' }); const content = await client.getContentItemById('item-id'); ``` -------------------------------- ### Include dc-delivery-sdk-js via CDN for legacy browsers Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Include the legacy CDN bundle for older browser support. ```html ``` -------------------------------- ### Transform Image URL with SDK Helpers Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Use SDK helper functions attached to Image properties to construct Dynamic Media URLs with transformations like width, height, sharpening, and format. ```javascript const ImageFormat = require('dc-delivery-sdk-js').ImageFormat; const imageUrl = content.body.imageProperty .url() .width(500) .height(500) .sharpen() .format(ImageFormat.WEBP) .build(); ``` -------------------------------- ### Strongly Typed Content with TypeScript Interfaces Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Define TypeScript interfaces that match your content types to get strongly typed content bodies when fetching data. This improves code safety and developer experience. ```typescript interface Banner extends ContentBody { heading: string; } client.getContentItem('ec5d12cc-b1bb-4df4-a7b3-fd7796326cfe'); ``` ```typescript interface BlogPost { title: string; category: string; date: string; ranking: number; description: string; readTime: number; } const res = await client .filterByContentType( 'https://example.com/blog-post-filter-and-sort' ) .request(); console.log(res); ``` -------------------------------- ### getByHierarchy Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ContentClient.md Fetches a complete hierarchy tree by root ID. Requires Content Delivery 2 or Fresh API. This method is ideal for retrieving the entire structure of a content hierarchy starting from a specific root. ```APIDOC ## getByHierarchy ### Description Fetches a complete hierarchy tree by root ID. Requires Content Delivery 2 or Fresh API. ### Method Not specified (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **requestParameters** (ByIdContentClientHierarchyRequest) - Required - Hierarchy request with `rootId` and optional parameters ### Return Type - **Promise>** - Tree structure with root and children ### Example ```typescript const hierarchy = await client.getByHierarchy({ rootId: '90d6fa96-6ce0-4332-b995-4e6c50b1e233' }); function printHierarchy(item) { console.log(item.content._meta.name); item.children.forEach(child => printHierarchy(child)); } printHierarchy(hierarchy); ``` ### Source `src/lib/ContentClient.ts:414` ``` -------------------------------- ### Construct Filter Request with JSON Path and Value Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ContentClient.md Use filterBy to start building a filter request by specifying a JSON path and a value. This method returns a FilterBy builder for chaining further filter, sort, or pagination operations. ```typescript const response = await client .filterBy('/_meta/schema', 'https://example.com/blog-post.json') .filterBy('/category', 'Technology') .sortBy('date', 'DESC') .page(10) .request({ depth: 'all' }); ``` -------------------------------- ### Include dc-delivery-sdk-js via CDN Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Include the SDK via a CDN for direct use in the browser. ```html ``` -------------------------------- ### Preview Staging Content by Timestamp Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Use StagingEnvironmentFactory to generate a staging environment pinned to a specific timestamp (epoch milliseconds). This environment can then be used with the ContentClient. ```javascript const factory = new StagingEnvironmentFactory( 'fhboh562c3tx1844c2ycknz96.staging.bigcontent.io' ); const stagingEnvironmentAtTimestamp = await factory.generateDomain({ timestamp: 1546264721816, }); const client = new ContentClient({ account: 'myaccount', stagingEnvironment: stagingEnvironmentAtTimestamp, }); ``` -------------------------------- ### Use Pinned Domain with ContentClient Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/StagingEnvironmentFactory.md Instantiate a ContentClient using a generated pinned staging environment domain to fetch content from that specific point in time. ```typescript // Use the pinned domain in ContentClient const client = new ContentClient({ account: 'myaccount', stagingEnvironment: domainWithSnapshot }); ``` -------------------------------- ### Initialize ContentClient for Content Delivery 2 API Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/README.md Instantiate the ContentClient with your hub name for CDv2 API access. This client is used to fetch content items by their delivery key. ```typescript import { ContentClient } from 'dc-delivery-sdk-js'; const client = new ContentClient({ hubName: 'myhub' }); const content = await client.getContentItemByKey('my-key'); ``` -------------------------------- ### Fetch Complete Hierarchy Tree by Root ID Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ContentClient.md Use `getByHierarchy` to retrieve an entire hierarchy structure starting from a specified root ID. This method requires Content Delivery 2 or Fresh API and returns a promise that resolves to the hierarchy content item. ```typescript getByHierarchy( requestParameters: ByIdContentClientHierarchyRequest ): Promise> ``` ```typescript const hierarchy = await client.getByHierarchy({ rootId: '90d6fa96-6ce0-4332-b995-4e6c50b1e233' }); function printHierarchy(item) { console.log(item.content._meta.name); item.children.forEach(child => printHierarchy(child)); } printHierarchy(hierarchy); ``` -------------------------------- ### Fetch and Process Hierarchical Content Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ContentModels.md Retrieves content items organized in a hierarchy, starting from a specified root ID. It includes a recursive function to process each item in the hierarchy, extracting relevant details like ID, title, category, and featured status, and building a nested structure of its children. ```typescript async function getBlogHierarchy() { const client = new ContentClient({ hubName: 'myhub' }); const hierarchy = await client.getByHierarchy({ rootId: 'blog-root' }); function processItem(item) { const post = item.content as BlogPost; return { id: post._meta.deliveryId, title: post.title, category: post.category, featured: post.featured, children: item.children.map(processItem) }; } return processItem(hierarchy); } ``` -------------------------------- ### Using ContentBody with TypeScript Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ContentModels.md Illustrates how to use ContentBody with TypeScript, showing type-safe access to fields for both generic and specifically typed content. ```typescript // Generic content (any fields) const item = await client.getContentItemById('id'); item.body.anyField; // Valid, any field // Typed content interface BlogPost extends ContentBody { title: string; author: string; content: string; publishDate: string; } const post = await client.getContentItemById('id'); post.body.title; // Type-safe post.body.nonExistent; // TypeScript error ``` -------------------------------- ### Constructing a Request Using an Object Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Demonstrates an alternative method for constructing a request by providing all filter, sort, page, and parameter options within a single configuration object. ```typescript const client = new ContentClient({ hubName: 'myhub', }); const res = await client.filterContentItems({ filterBy: [ { path: '/_meta/schema', value: 'https://example.com/blog-post-filter-and-sort', }, { path: '/category', value: 'Homewares', }, ], sortBy: { key: 'readTime', order: 'DESC', }, page: { size: 2, }, parameters: { format: 'inlined', depth: 'all', }, }); console.log(res); ``` -------------------------------- ### Build URL with Custom Template and Parameters Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/ImageUrlBuilder.md Combines a custom transformation template with specific parameters to create a tailored image URL. ```typescript const url = image.url() .template('myTemplate') .parameter('locale', 'en-US') .parameter('variant', 'dark') .build(); ``` -------------------------------- ### Initialize ContentClient for Content Delivery 1 API Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/README.md Instantiate the ContentClient with your account name for CDv1 API access. This client is used to fetch content items by their delivery ID. ```typescript const client = new ContentClient({ account: 'myaccount' }); const content = await client.getContentItemById('item-id'); ``` -------------------------------- ### StagingEnvironmentFactory Constructor Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/StagingEnvironmentFactory.md Creates a new StagingEnvironmentFactory instance. It requires a virtual staging environment hostname and accepts an optional configuration object. ```APIDOC ## StagingEnvironmentFactory Constructor Creates a new StagingEnvironmentFactory instance. ### Parameters #### Path Parameters - **stagingEnvironment** (string) - Required - Virtual Staging Environment hostname (e.g., 'abc123.staging.bigcontent.io') - **config** (StagingEnvironmentFactoryConfig) - Optional - Optional configuration object ``` -------------------------------- ### Using filterByContentType, filterBy, and sortBy Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/README.md Demonstrates constructing a request using chained filter and sort methods, followed by executing the request. ```APIDOC ## GET /_meta/schema ### Description Retrieves content items filtered by schema, category, sorted by a specified key and order, and paginated. ### Method GET ### Endpoint /_meta/schema ### Parameters #### Query Parameters - **format** (string) - Optional - Specifies the response format. Example: 'inlined'. - **depth** (string) - Optional - Specifies the depth of related content to include. Example: 'all'. #### Request Body This method does not explicitly define a request body in the documentation. The filtering and sorting are applied via chained method calls. ### Request Example ```ts const client = new ContentClient({ hubName: 'myhub', }); const res = await client .filterByContentType('https://example.com/blog-post-filter-and-sort') .filterBy('/category', 'Homewares') .sortBy('readTime', 'DESC') .page(2) .request({ format: 'inlined', depth: 'all', }); console.log(res); ``` ### Response #### Success Response (200) - **responses** (array) - An array of content item objects. - **content** (object) - The content of a single item. - **_meta** (object) - Metadata for the content item. - **name** (string) - The name of the content item. - **schema** (string) - The schema of the content item. - **deliveryKey** (string) - The delivery key for the content item. - **deliveryId** (string) - The delivery ID for the content item. - **title** (string) - The title of the content item. - **category** (string) - The category of the content item. - **date** (string) - The date associated with the content item. - **ranking** (number) - The ranking of the content item. - **description** (string) - A description of the content item. - **readTime** (number) - The read time of the content item. - **page** (object) - Pagination information. - **responseCount** (number) - The number of items returned in this response. - **next** (function) - A function to retrieve the next page of results. - **nextCursor** (string) - The cursor for the next page. #### Response Example ```json { "responses": [ { "content": { "_meta": { "name": "Homewares blog post", "schema": "https://example.com/blog-post-filter-and-sort", "deliveryKey": "new/homeware-collection/about", "deliveryId": "1024dc7a-f255-46a7-b374-be85081a562f" }, "title": "All about our new homeware collection", "category": "Homewares", "date": "2021-05-05", "ranking": 4, "description": "Our new homeware has just landed. Find out how you can fill your home with some exciting designs.", "readTime": 5 } }, { "content": { "_meta": { "name": "Summer collection blog", "schema": "https://example.com/blog-post-filter-and-sort", "deliveryKey": "new/summer-fashion/about", "deliveryId": "fb466729-b604-496f-be36-521013a752d2" }, "title": "Our new summer collection blog", "category": "Homewares", "date": "2021-05-05", "ranking": 2, "description": "A sneak peak at our new summer collection", "readTime": 4 } } ], "page": { "responseCount": 2, "next": () => // next page "nextCursor": "eyJzb3J0S2V5IjoiXCIgNUAmJTYwOTJiZjBhNGNlZGZkMDAwMWVhZTY3ZCIsIml0ZW1JZCI6ImFtcHByb2R1Y3QtZG9jOjg2Y2E2YjgxLTJkOGYtNDRiMi1iNGQ1LTFlZjU0MzgzMzMyMyJ9" } } ``` ``` -------------------------------- ### Initialize ContentClient for Fresh API with Retry Configuration Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/README.md Configure the ContentClient for the Fresh API, including a hub name, API key, and custom retry logic. The retry configuration specifies the number of retries and a delay function based on the retry count. ```typescript const client = new ContentClient({ hubName: 'myhub', apiKey: 'my-api-key', retryConfig: { retries: 5, retryDelay: (count) => Math.pow(2, count) * 1000 } }); ``` -------------------------------- ### Direct Image Instantiation (Internal Use) Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/Media.md This shows the direct instantiation of an Image object, which is primarily for internal SDK use. It requires image data and client configuration. ```typescript const image = new Image({ defaultHost: 'images.example.com', endpoint: 'account', name: 'image-id', id: 'image-id' }, config); ``` -------------------------------- ### page (with size and optional cursor) Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/FilterBy.md Sets the page size and optional cursor for pagination. The maximum page size is 12. ```APIDOC ## page (with size and optional cursor) ### Description Sets the page size and optional cursor for pagination. Maximum page size is 12. ### Method Signature ```typescript page(size: number, cursor?: string): FilterBy ``` ### Parameters #### Query Parameters - **size** (number) - Required - Number of items per page (max 12) - **cursor** (string) - Optional - Cursor token for pagination ### Return Type - **FilterBy** - This builder ### Example ```typescript // First page const page1 = await client .filterByContentType('https://example.com/blog-post.json') .page(10) .request(); // Next page using cursor const page2 = await client .filterByContentType('https://example.com/blog-post.json') .page(10, page1.page.nextCursor) .request(); ``` ``` -------------------------------- ### Generate Video Thumbnails Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/Media.md Creates various sizes and formats of video thumbnails, including WEBP for better compression. ```typescript import { Video, ImageFormat } from 'dc-delivery-sdk-js'; async function getVideoThumbnails(content) { if (!Video.isVideo(content.body.video)) { return null; } const video = content.body.video; return { tiny: video.thumbnail() .width(100) .height(56) .format(ImageFormat.JPEG) .build(), small: video.thumbnail() .width(320) .height(180) .quality(75) .format(ImageFormat.WEBP) .build(), large: video.thumbnail() .width(800) .height(450) .quality(85) .format(ImageFormat.WEBP) .build() }; } ``` -------------------------------- ### Instantiate StagingEnvironmentFactory Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/StagingEnvironmentFactory.md Create a new StagingEnvironmentFactory instance with the virtual staging environment hostname. ```typescript import { StagingEnvironmentFactory } from 'dc-delivery-sdk-js'; const factory = new StagingEnvironmentFactory( 'abc123xyz789.staging.bigcontent.io' ); ``` -------------------------------- ### Build Video Thumbnail URL Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/overview.md Generate a thumbnail URL for a video resource. Specify dimensions and format for the thumbnail image. ```typescript const thumbnailUrl = video.thumbnail() .width(300) .height(169) .format(ImageFormat.JPEG) .build(); ``` -------------------------------- ### Content Client Configuration for v2 Fresh API Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/configuration.md Extends v2 configuration with optional API key and retry settings for the Fresh API. Configure retry logic for handling throttled responses. ```typescript interface ContentClientConfigV2Fresh extends ContentClientConfigV2 { apiKey?: string; retryConfig?: ContentClientRetryConfig; } interface ContentClientRetryConfig { retries?: number; retryDelay?: (retryCount: number, error: AxiosError) => number; retryCondition?: (error: AxiosError) => boolean | Promise; } ``` ```typescript const client = new ContentClient({ hubName: 'myhub', apiKey: 'my-fresh-api-key', retryConfig: { retries: 5, retryDelay: (retryCount) => Math.pow(2, retryCount) * 1000, retryCondition: (error) => error?.response?.status === 429 } }); ``` -------------------------------- ### Fetch Content Items by Keys Source: https://github.com/amplience/dc-delivery-sdk-js/blob/master/_autodocs/api-reference/MultiFetchPatterns.md Retrieve multiple content items using their delivery keys. This is useful for fetching items like articles or pages identified by a path. ```typescript const keys = ['blog/article-1', 'blog/article-2', 'blog/article-3']; const response = await client.getContentItemsByKey(keys); // Check for successful fetches const items = response.responses .filter(r => 'content' in r) .map(r => r.content); ```