### Full Hub Management Example Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/Hub.md A comprehensive example demonstrating hub retrieval, listing repositories, creating an event, and updating hub details using the SDK. ```typescript import { DynamicContent, Event, Status } from 'dc-management-sdk-js'; async function manageHub() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); const hub = await client.hubs.get('hub-id-123'); console.log('Hub:', hub.label); // List repositories const repos = await hub.related.contentRepositories.list({ size: 5 }); repos.getItems().forEach(repo => { console.log('Repository:', repo.name); }); // Create an event const event = new Event(); event.name = 'Summer Sale 2024'; event.start = '2024-06-01T00:00:00.000Z'; event.end = '2024-08-31T23:59:59.999Z'; const created = await hub.related.events.create(event); console.log('Created event:', created.id); // Update hub hub.description = 'Updated description'; const updated = await hub.related.update(hub); } manageHub().catch(console.error); ``` -------------------------------- ### Complete SDK Configuration Example Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/configuration.md A comprehensive example demonstrating how to create a DynamicContent client with custom Axios instance configuration, including timeouts, headers, and request logging interceptors. This setup allows for fine-grained control over SDK behavior. ```typescript import { DynamicContent } from 'dc-management-sdk-js'; import axios from 'axios'; // Create Axios instance with custom configuration const axiosInstance = axios.create({ timeout: 15000, headers: { 'User-Agent': 'MyApp/1.0' } }); // Add request logging axiosInstance.interceptors.request.use(config => { console.log(`[${new Date().toISOString()}] ${config.method?.toUpperCase()} ${config.url}`); return config; }); // Create client with all configuration const client = new DynamicContent( { client_id: process.env.DC_CLIENT_ID, client_secret: process.env.DC_CLIENT_SECRET }, { apiUrl: process.env.DC_API_URL || 'https://api.amplience.net/v2/content', authUrl: process.env.DC_AUTH_URL || 'https://auth.amplience.net' }, axiosInstance.defaults ); export { client }; ``` -------------------------------- ### Install dc-management-sdk-js Source: https://github.com/amplience/dc-management-sdk-js/blob/master/README.md Install the SDK using npm. This is the first step before using the library. ```sh npm install dc-management-sdk-js --save ``` -------------------------------- ### Installation Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/README.md Install the DC Management SDK for JavaScript using npm. ```APIDOC ## Installation ```bash npm install dc-management-sdk-js ``` ``` -------------------------------- ### Manage Workflow States Example Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/WorkflowState.md Demonstrates a complete workflow for managing workflow states, including fetching, updating, and retrieving associated hubs. This example requires client credentials for authentication. ```typescript import { DynamicContent, WorkflowState } from 'dc-management-sdk-js'; async function manageWorkflowStates() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); const state = await client.workflowStates.get('state-id'); console.log('State:', state.label); console.log('Color:', state.color); // Update the state state.label = 'Updated State Label'; const updated = await state.related.update(state); console.log('Updated'); // Get the hub const hub = await updated.related.hub(); console.log('Hub:', hub.label); } manageWorkflowStates().catch(console.error); ``` -------------------------------- ### Basic Usage Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/README.md Demonstrates basic usage of the SDK, including client creation, listing hubs, getting content items, and creating content. ```APIDOC ## Basic Usage ```typescript import { DynamicContent, ContentItem } from 'dc-management-sdk-js'; // Create client const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET }); // List hubs const hubs = await client.hubs.list(); // Get content items const item = await client.contentItems.get('item-id'); // Create content const repo = await client.contentRepositories.get('repo-id'); const newItem = new ContentItem(); newItem.label = 'My Item'; newItem.body = { /* content */ }; const created = await repo.related.contentItems.create(newItem); ``` ``` -------------------------------- ### Full Folder Organization Example Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/Folder.md Demonstrates a comprehensive workflow for interacting with folders, including retrieving repositories, listing, creating, and accessing subfolders and content items. ```typescript import { DynamicContent, Folder, ContentItem } from 'dc-management-sdk-js'; async function organizeFolders() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); const repo = await client.contentRepositories.get('repo-id'); // Get top-level folders const topFolders = await repo.related.folders.list({ page: 0, size: 10 }); const folder = topFolders.getItems()[0]; console.log('Folder:', folder.name); // Get parent folder try { const parent = await folder.related.folders.parent(); console.log('Parent folder:', parent.name); } catch (err) { console.log('No parent folder (root level)'); } // List subfolders const subfolders = await folder.related.folders.list({ page: 0, size: 10 }); console.log(`Folder has ${subfolders.getItems().length} subfolders`); // Create a subfolder const subfolder = new Folder(); subfolder.name = 'Articles'; const created = await folder.related.folders.create(subfolder); console.log('Created subfolder:', created.id); // List items in subfolder const items = await created.related.contentItems.list({ page: 0, size: 20 }); console.log(`Subfolder has ${items.getItems().length} items`); } organizeFolders().catch(console.error); ``` -------------------------------- ### Basic SDK Usage Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/README.md Demonstrates basic usage of the SDK, including client creation, listing hubs, getting content items, and creating new content. ```typescript import { DynamicContent, ContentItem } from 'dc-management-sdk-js'; // Create client const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET }); // List hubs const hubs = await client.hubs.list(); // Get content items const item = await client.contentItems.get('item-id'); // Create content const repo = await client.contentRepositories.get('repo-id'); const newItem = new ContentItem(); newItem.label = 'My Item'; newItem.body = { /* content */ }; const created = await repo.related.contentItems.create(newItem); ``` -------------------------------- ### Manage Edition Lifecycle Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/Edition.md Demonstrates how to get an edition, list and create slots, update edition details, and schedule an edition. Requires client credentials for authentication. ```typescript import { DynamicContent, Edition, EditionSlotRequest } from 'dc-management-sdk-js'; async function manageEdition() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); const edition = await client.editions.get('edition-id'); console.log('Edition:', edition.name, 'Status:', edition.publishingStatus); // List slots const slots = await edition.related.slots.list({ page: 0, size: 10 }); console.log(`Edition has ${slots.getItems().length} slots`); slots.getItems().forEach(slot => { console.log('Slot:', slot.label, 'Item:', slot.contentItemIds); }); // Create slots const slotRequests: EditionSlotRequest[] = [ { contentItemId: 'item-1', slotName: 'main-hero' }, { contentItemId: 'item-2', slotName: 'featured' } ]; const createdSlots = await edition.related.slots.create(slotRequests); console.log('Created slots'); // Update edition edition.comment = 'Updated comment'; const updated = await edition.related.update(edition); // Schedule the edition try { await updated.related.schedule(); console.log('Edition scheduled successfully'); } catch (err) { console.error('Failed to schedule:', err); } // Later, unschedule if needed // await updated.related.unschedule(); } manageEdition().catch(console.error); ``` -------------------------------- ### Full Content Repository Management Example Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/ContentRepository.md Demonstrates a comprehensive workflow including fetching a repository, listing items, creating folders, creating content items, and assigning content types using the DC Management SDK. ```typescript import { DynamicContent, ContentItem, Folder } from 'dc-management-sdk-js'; async function manageRepository() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); const repository = await client.contentRepositories.get('repo-id-123'); console.log('Repository:', repository.label); console.log('Features:', repository.features); // List items const items = await repository.related.contentItems.list({ page: 0, size: 50 }); console.log(`Found ${items.getItems().length} items`); // Create a folder const folder = new Folder(); folder.name = 'Blog Posts'; const createdFolder = await repository.related.folders.create(folder); console.log('Created folder:', createdFolder.id); // Create a content item const item = new ContentItem(); item.label = 'Welcome Post'; item.body = { _meta: { schema: 'https://example.com/blog-post-schema.json' }, title: 'Welcome to Our Blog', excerpt: 'First post', content: 'Blog content here...' }; const created = await repository.related.contentItems.create(item); console.log('Created item:', created.id, 'Version:', created.version); // Assign a content type const updated = await repository.related.contentTypes.assign('type-id-123'); console.log('Assigned content type'); } manageRepository().catch(console.error); ``` -------------------------------- ### Full Event Management Example Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/Event.md Demonstrates a comprehensive workflow for managing events, including creation, retrieval, edition management, updating, and archiving using the SDK. ```typescript import { DynamicContent, Event, Edition } from 'dc-management-sdk-js'; async function manageEvent() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); const hub = await client.hubs.get('hub-id'); // Create an event const event = new Event(); event.name = 'Black Friday 2024'; event.comment = 'Annual black friday sale'; event.start = '2024-11-24T00:00:00.000Z'; event.end = '2024-11-29T23:59:59.999Z'; event.brief = 'https://example.com/black-friday-requirements'; const created = await hub.related.events.create(event); console.log('Created event:', created.id); // Get the event const retrieved = await client.events.get(created.id); // Create an edition within the event const edition = new Edition(); edition.name = 'Early Access'; edition.start = '2024-11-22T00:00:00.000Z'; edition.end = '2024-11-23T23:59:59.999Z'; const createdEdition = await retrieved.related.editions.create(edition); console.log('Created edition:', createdEdition.id); // List all editions for the event const editions = await retrieved.related.editions.list(); editions.getItems().forEach(ed => { console.log('Edition:', ed.name); }); // Update the event retrieved.name = 'Black Friday & Cyber Monday 2024'; retrieved.end = '2024-12-02T23:59:59.999Z'; const updated = await retrieved.related.update(retrieved); console.log('Updated event'); // Archive the event const archived = await updated.related.archive(); console.log('Archived event'); } manageEvent().catch(console.error); ``` -------------------------------- ### Full Snapshot Management Example Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/Snapshot.md Demonstrates how to initialize the SDK, retrieve a snapshot by ID, access its properties, and fetch related resources like the Hub and a specific content item from the snapshot. Ensure your environment variables CLIENT_ID and CLIENT_SECRET are set. ```typescript import { DynamicContent } from 'dc-management-sdk-js'; async function manageSnapshot() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); const snapshot = await client.snapshots.get('snapshot-id'); console.log('Snapshot:', snapshot.id); console.log('Created:', snapshot.createdDate); console.log('Comment:', snapshot.comment); console.log('Type:', snapshot.type); // Get the hub const hub = await snapshot.related.hub(); console.log('Hub:', hub.label); // Get a specific content item from snapshot const item = await snapshot.related.snapshotContentItem('item-id'); console.log('Content item from snapshot:', item.label); console.log('Version:', item.version); } manageSnapshot().catch(console.error); ``` -------------------------------- ### Full Content Type Management Example Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/ContentType.md Demonstrates a complete workflow for managing a content type, including initialization, retrieval, updating settings, schema management, archiving, and unarchiving. ```typescript import { DynamicContent, ContentType, ContentTypeSettings } from 'dc-management-sdk-js'; async function manageContentType() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); const contentType = await client.contentTypes.get('type-id'); console.log('Content Type:', contentType.contentTypeUri); console.log('Status:', contentType.status); // Update settings if (!contentType.settings) { contentType.settings = {}; } contentType.settings.label = 'Article'; contentType.settings.icons = [ { size: 32, url: 'https://example.com/icons/article-32.png' }, { size: 64, url: 'https://example.com/icons/article-64.png' } ]; contentType.settings.visualizations = [ { label: 'Default Visualization', templatedUri: 'https://example.com/visualizations/article', default: true } ]; contentType.settings.cards = [ { label: 'Article Card', templatedUri: 'https://example.com/cards/article', default: true } ]; const updated = await contentType.related.update(contentType); console.log('Updated content type'); // Get schema const schema = await updated.related.contentTypeSchema.get(); console.log('Schema version:', schema.cachedSchema?.['$id']); // Archive const archived = await updated.related.archive(); console.log('Archived'); // Unarchive const unarchived = await archived.related.unarchive(); console.log('Unarchived'); } manageContentType().catch(console.error); ``` -------------------------------- ### Custom HTTP Client Implementation Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/HttpClient.md Example of implementing a custom HTTP client using the `HttpClient` interface, demonstrating how to integrate with other libraries like `node-fetch`. ```APIDOC ## Custom HTTP Client Implementation Implement `HttpClient` for custom HTTP handling: ```typescript import { HttpClient, HttpRequest, HttpResponse, HttpMethod, DynamicContent } from 'dc-management-sdk-js'; import fetch from 'node-fetch'; class CustomHttpClient implements HttpClient { async request(request: HttpRequest): Promise { const response = await fetch(request.url, { method: request.method, headers: { 'Content-Type': 'application/json', ...request.headers }, body: request.data ? JSON.stringify(request.data) : undefined }); return { status: response.status, statusText: response.statusText, headers: Object.fromEntries(response.headers), data: await response.json() }; } } const client = new DynamicContent( { client_id, client_secret }, undefined, new CustomHttpClient() ); ``` ``` -------------------------------- ### OAuth2 Authentication Usage Examples Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/Authentication.md Demonstrates two methods for authenticating with the SDK using OAuth2: directly in the DynamicContent constructor (recommended) or by creating an Oauth2AuthHeaderProvider instance separately. ```typescript import { DynamicContent, Oauth2AuthHeaderProvider } from 'dc-management-sdk-js'; // Method 1: Direct in DynamicContent constructor (recommended) const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET }); // Method 2: Using Oauth2AuthHeaderProvider directly const authProvider = new Oauth2AuthHeaderProvider({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET }); const header = await authProvider.getAuthHeader(); console.log(header); // 'Bearer eyJhbGc...' ``` -------------------------------- ### Manage Content Editions Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/README.md This example shows how to create a new edition for an event, add content item slots to it, and then schedule the edition for release. Ensure the event ID and content item IDs are valid. ```typescript const event = await client.events.get('event-id'); const edition = new Edition(); edition.name = 'Launch'; edition.start = '2024-06-01T00:00:00Z'; edition.end = '2024-06-30T23:59:59Z'; const created = await event.related.editions.create(edition); // Add slots await created.related.slots.create([ { contentItemId: 'item-1', slotName: 'hero' } ]); // Schedule await created.related.schedule(); ``` -------------------------------- ### Create an Event (TypeScript) Source: https://github.com/amplience/dc-management-sdk-js/blob/master/README.md Example demonstrating how to create a new event using the SDK in TypeScript. It involves fetching a hub, instantiating an Event, setting its properties, and then creating it via the hub's related events. ```typescript import { DynamicContent, Event } from 'dc-management-sdk-js'; async function createEvent() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); const hubs = await client.hubs.list(); const hub = hubs.getItems()[0]; let event = new Event(); event.name = 'happy new year'; event.start = '2019-01-01T00:00:00.000Z'; event.end = '2019-01-01T23:59:59.999Z'; event = await hub.related.events.create(event); console.log(event); } createEvent(); ``` -------------------------------- ### Manage Webhook Lifecycle (Usage Example) Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/Webhook.md Demonstrates how to retrieve, update (disable/re-enable), and potentially delete a webhook using the DC Management SDK JS. Requires client credentials for authentication. ```typescript import { DynamicContent, Webhook, WebhookHeader } from 'dc-management-sdk-js'; async function manageWebhook() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); const webhook = await client.hubs.get('hub-id') .then(h => h.related.webhooks.list()) .then(w => w.getItems()[0]); console.log('Webhook:', webhook.label); console.log('Events:', webhook.events); console.log('Handlers:', webhook.handlers); console.log('Active:', webhook.active); // Disable the webhook webhook.active = false; const updated = await webhook.related.update(webhook); // Re-enable the webhook updated.active = true; const reEnabled = await updated.related.update(updated); // Delete the webhook // await reEnabled.related.delete(); } manageWebhook().catch(console.error); ``` -------------------------------- ### Create an Event (JavaScript) Source: https://github.com/amplience/dc-management-sdk-js/blob/master/README.md Example demonstrating how to create a new event using the SDK in JavaScript. It uses promises to chain operations: listing hubs, selecting a hub, creating an event object, and then creating the event via the hub's related events. ```javascript var dc = require('dc-management-sdk-js'); function createEvent() { var client = new dc.DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); client.hubs .list() .then(function (hubs) { var hub = hubs.getItems()[0]; var event = new dc.Event(); event.name = 'happy new year'; event.start = '2019-01-01T00:00:00.000Z'; event.end = '2019-01-01T23:59:59.999Z'; return hub.related.events.create(event); }) .then(function (event) { console.log(event); }); } createEvent(); ``` -------------------------------- ### Get Hub Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/ContentRepository.md Retrieves the Hub that contains the current content repository. ```APIDOC ## Get Hub ### Description Retrieves the Hub that contains the current content repository. ### Method `GET` (Implicit via related resource access) ### Endpoint `/hubs/{hubId}` (Implicit) ### Parameters None directly on this call, but relies on the repository's context. ### Response #### Success Response - **Hub** (Hub) - The Hub resource object. ### Response Example ```json { "id": "hub-id-123", "label": "My Hub", "status": "ACTIVE" } ``` ``` -------------------------------- ### PAT Authentication Usage Examples Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/Authentication.md Shows two ways to authenticate using a Personal Access Token (PAT): directly within the DynamicContent constructor or by instantiating PatTokenAuthHeaderProvider separately. ```typescript import { DynamicContent, PatTokenAuthHeaderProvider } from 'dc-management-sdk-js'; // Method 1: Direct in DynamicContent constructor (recommended) const client = new DynamicContent({ patToken: process.env.PAT_TOKEN }); // Method 2: Using PatTokenAuthHeaderProvider directly const authProvider = new PatTokenAuthHeaderProvider(process.env.PAT_TOKEN); const header = await authProvider.getAuthHeader(); console.log(header); // 'Bearer pat_...' ``` -------------------------------- ### Execute HTTP Request Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/HttpClient.md Demonstrates how to use the `request` method of an `HttpClient` to make a GET request to the '/hubs' endpoint and log the response status and data. ```typescript const response = await httpClient.request({ method: HttpMethod.GET, url: '/hubs' }); console.log('Status:', response.status); console.log('Data:', response.data); ``` -------------------------------- ### Configure HTTP Client with Axios Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/configuration.md Pass Axios configuration directly to the SDK constructor for advanced HTTP settings like timeouts, proxies, and custom headers. Requires 'axios' and 'dc-management-sdk-js' to be installed. ```typescript import { DynamicContent } from 'dc-management-sdk-js'; import { AxiosRequestConfig } from 'axios'; const axiosConfig: AxiosRequestConfig = { timeout: 10000, proxy: { protocol: 'http', host: 'proxy.example.com', port: 8080 }, headers: { 'User-Agent': 'my-app/1.0' } }; const client = new DynamicContent( { client_id, client_secret }, undefined, // dcConfig axiosConfig ); ``` -------------------------------- ### Clone Content with Updated Links Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/ContentGraph.md This example demonstrates cloning a content item and all its linked items using `ContentGraph.deepCopy`. It shows how to provide a custom function to create new content items in the target repository. ```typescript import { DynamicContent, ContentGraph, ContentItem } from 'dc-management-sdk-js'; async function cloneContentWithUpdatedLinks() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); const repo = await client.contentRepositories.get('repo-id'); const itemToClone = await client.contentItems.get('item-id'); // Deep copy the item and all its linked items const idMap = await ContentGraph.deepCopy( [itemToClone.id], client.contentItems.get, async (original, body) => { const clone = new ContentItem(); clone.label = `${original.label} (Clone)`; clone.body = body; // Body has already been updated with new link IDs return repo.related.contentItems.create(clone); } ); console.log('Cloned items created:'); Object.entries(idMap).forEach(([oldId, newId]) => { console.log(`${oldId} -> ${newId}`); }); } cloneContentWithUpdatedLinks().catch(console.error); ``` -------------------------------- ### List Snapshots for a Hub Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/Snapshot.md Shows how to retrieve a list of snapshots associated with a specific hub. This example requires the hub ID and demonstrates iterating through the retrieved snapshots to log their details. Ensure your environment variables CLIENT_ID and CLIENT_SECRET are set. ```typescript import { DynamicContent } from 'dc-management-sdk-js'; async function listHubSnapshots() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); const hub = await client.hubs.get('hub-id'); // Snapshots are typically accessed via snapshots endpoint const snapshots = await hub.related.snapshots.list({ page: 0, size: 20 }); snapshots.getItems().forEach(snap => { console.log('Snapshot:', snap.id); console.log('Created:', snap.createdDate); console.log('Comment:', snap.comment); }); } listHubSnapshots().catch(console.error); ``` -------------------------------- ### Custom HTTP Client Implementation Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/HttpClient.md Provides an example of a custom `HttpClient` implementation using `node-fetch`. This allows for custom request/response handling, such as setting specific headers or parsing JSON responses. ```typescript import { HttpClient, HttpRequest, HttpResponse, HttpMethod, DynamicContent } from 'dc-management-sdk-js'; import fetch from 'node-fetch'; class CustomHttpClient implements HttpClient { async request(request: HttpRequest): Promise { const response = await fetch(request.url, { method: request.method, headers: { 'Content-Type': 'application/json', ...request.headers }, body: request.data ? JSON.stringify(request.data) : undefined }); return { status: response.status, statusText: response.statusText, headers: Object.fromEntries(response.headers), data: await response.json() }; } } const client = new DynamicContent( { client_id, client_secret }, undefined, new CustomHttpClient() ); ``` -------------------------------- ### OAuth2 Token Management Example Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/Authentication.md Illustrates how the SDK automatically caches and refreshes OAuth2 tokens. Subsequent requests reuse cached tokens, and expired tokens are refreshed on demand. ```typescript // First request - acquires token const hubs1 = await client.hubs.list(); // Subsequent requests - reuses cached token const hubs2 = await client.hubs.list(); // After token expiry - automatically refreshes // (may take a moment longer as new token is acquired) const hubs3 = await client.hubs.list(); ``` -------------------------------- ### Create Edition via Event Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/Edition.md Shows how to create a new edition associated with an existing event. This involves fetching an event and then creating an Edition object with relevant properties like name, comment, start, and end dates. ```typescript import { DynamicContent, Event, Edition } from 'dc-management-sdk-js'; async function createEditionViaEvent() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); const event = await client.events.get('event-id'); // Create an edition for the event const edition = new Edition(); edition.name = 'Launch Edition'; edition.comment = 'Initial product launch'; edition.start = event.start; edition.end = event.end; edition.activeEndDate = true; const created = await event.related.editions.create(edition); console.log('Created edition:', created.id); // List all editions for the event const editions = await event.related.editions.list(); console.log(`Event has ${editions.getItems().length} editions`); } createEditionViaEvent().catch(console.error); ``` -------------------------------- ### Configure HTTP Client with Custom Implementation Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/configuration.md Implement the 'HttpClient' interface for complete control over HTTP requests. This allows for custom request logic and response handling. Requires 'dc-management-sdk-js' to be installed. ```typescript import { DynamicContent, HttpClient, HttpRequest, HttpResponse } from 'dc-management-sdk-js'; class CustomHttpClient implements HttpClient { async request(request: HttpRequest): Promise { // Custom implementation console.log('Request:', request.method, request.url); // ... make the HTTP request return response; } } const client = new DynamicContent( { client_id, client_secret }, undefined, new CustomHttpClient() ); ``` -------------------------------- ### Retrieve Hub Containing Snapshot Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/Snapshot.md Use this method to get the Hub that contains the current snapshot. No specific setup is required beyond having a snapshot object. ```typescript related.hub(): Promise ``` ```typescript const hub = await snapshot.related.hub(); ``` -------------------------------- ### Create and List Events Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/Hub.md Use this snippet to create new events or list existing events within a hub. Ensure the Event object has required properties like name, start, and end dates. ```typescript const event = new Event(); event.name = 'Christmas Sale'; event.start = '2024-12-01T00:00:00.000Z'; event.end = '2024-12-31T23:59:59.999Z'; const created = await hub.related.events.create(event); const events = await hub.related.events.list({ page: 0, size: 10 }); ``` -------------------------------- ### Get Content Repository Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/ContentItem.md Get the content repository that contains this content item. ```APIDOC ## Get Content Repository ### Description Get the content repository containing this item. ### Method `related.contentRepository(): Promise` ### Response #### Success Response (200) - **ContentRepository** - The content repository object. ### Request Example ```typescript const repository = await contentItem.related.contentRepository(); console.log('Repository:', repository.name); ``` ``` -------------------------------- ### Get Publishing Job Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/PublishingJob.md Retrieves a specific publishing job by its ID. ```APIDOC ## Get Publishing Job ### Endpoint `GET /publishing-jobs/{jobId}` ### Parameters #### Path Parameters - **jobId** (string) - Required - The ID of the publishing job to retrieve. ``` -------------------------------- ### Get Localizations Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/ContentItem.md Retrieve all localizations of the current content item, with optional pagination. ```APIDOC ## Get Localizations ### Description Retrieve localizations of this content item. ### Method `related.localizations(options?: Pageable): Promise>` ### Parameters * **options** (Pageable) - Optional - Pagination options (e.g., `{ page: 0, size: 10 }`). ### Response #### Success Response (200) - **Page** - A paginated list of localized content items. ### Request Example ```typescript const localizations = await contentItem.related.localizations({ page: 0, size: 10 }); localizations.getItems().forEach(local => { console.log('Locale:', local.locale); }); ``` ``` -------------------------------- ### Initialize Client with Default API and Auth URLs Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/configuration.md Demonstrates client initialization with default production API and authentication URLs. These are the default values and do not need to be explicitly provided. ```typescript const client = new DynamicContent( { client_id, client_secret }, { apiUrl: 'https://api.amplience.net/v2/content', authUrl: 'https://auth.amplience.net' } ); ``` -------------------------------- ### Get Hierarchy Children Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/DynamicContent.md Retrieves the child hierarchy information for a given content item ID. ```APIDOC ## GET /hierarchies/children/{id} ### Description Retrieves the child hierarchy information for a given content item ID. ### Method GET ### Endpoint /hierarchies/children/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the content item. ### Response #### Success Response (200) - **HierarchyChildren** - An object containing the child hierarchy information. ``` -------------------------------- ### Get Hierarchy Parents Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/DynamicContent.md Retrieves the parent hierarchy information for a given content item ID. ```APIDOC ## GET /hierarchies/parents/{id} ### Description Retrieves the parent hierarchy information for a given content item ID. ### Method GET ### Endpoint /hierarchies/parents/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the content item. ### Response #### Success Response (200) - **HierarchyParents** - An object containing the parent hierarchy information. ``` -------------------------------- ### Get Specific Version of Content Item Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/ContentItem.md Retrieve a specific version of the content item using its version number. ```APIDOC ## Get Specific Version of Content Item ### Description Retrieve a specific version of the content item. ### Method `related.contentItemVersion(version: number): Promise` ### Parameters * **version** (number) - Required - The version number of the content item to retrieve. ### Response #### Success Response (200) - **ContentItem** - The requested version of the content item. ### Request Example ```typescript const version2 = await contentItem.related.contentItemVersion(2); console.log('Version 2 body:', version2.body); ``` ``` -------------------------------- ### Get Content Repository Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/ContentItem.md Retrieves the content repository that contains the current content item. Use this to access repository-level information. ```typescript const repository = await contentItem.related.contentRepository(); console.log('Repository:', repository.name); ``` -------------------------------- ### Initialize Client with PAT Environment Variables Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/configuration.md Initialize the client using a Personal Access Token stored in an environment variable. Ensure DC_PAT_TOKEN is set in your environment. ```typescript const client = new DynamicContent({ patToken: process.env.DC_PAT_TOKEN }); ``` -------------------------------- ### Publish Content Item and Get Job Location Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/PublishingJob.md Publishes a content item and returns a PublishingJobLocation. This can be used to track the job's progress. ```typescript import { DynamicContent } from 'dc-management-sdk-js'; async function publishContentItem() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); const item = await client.contentItems.get('item-id'); // Publish the item const jobLocation = await item.related.publish(); console.log('Publishing job location:', jobLocation); // Extract job ID from location if needed // and poll for job status if (jobLocation?.id) { const job = await client.publishingJob.get(jobLocation.id); console.log('Job state:', job.state); } } publishContentItem().catch(console.error); ``` -------------------------------- ### Full Workflow: Create and Publish Content Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/DynamicContent.md Demonstrates a complete workflow for creating and publishing a content item. Ensure you have valid client credentials and content types configured. ```typescript import { DynamicContent, ContentItem } from 'dc-management-sdk-js'; async function createAndPublishContent() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); // Get a hub const hubs = await client.hubs.list(); const hub = hubs.getItems()[0]; // Get a repository from the hub const repos = await hub.related.contentRepositories.list(); const repo = repos.getItems()[0]; // Create a content item const item = new ContentItem(); item.label = 'My Content'; item.body = { _meta: { schema: 'https://github.com/amplience/dc-content-types/blob/master/content-types/hero-banner.json', }, heading: 'Welcome', }; const created = await repo.related.contentItems.create(item); console.log('Created:', created.id); // Publish the item const jobLocation = await created.related.publish(); console.log('Publishing to:', jobLocation); } createAndPublishContent().catch(console.error); ``` -------------------------------- ### Get and Check Publishing Job Status Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/PublishingJob.md Retrieves a publishing job by its ID and logs its details and state. Useful for monitoring job progress. ```typescript import { DynamicContent, PublishingJobStatus } from 'dc-management-sdk-js'; async function checkPublishingJob() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); const job = await client.publishingJob.get('job-id'); console.log('Job ID:', job.id); console.log('State:', job.state); console.log('Created:', job.createdDate); console.log('Created by:', job.createdBy); switch (job.state) { case PublishingJobStatus.PENDING: console.log('Job is pending...'); break; case PublishingJobStatus.IN_PROGRESS: console.log('Job is in progress...'); break; case PublishingJobStatus.COMPLETED: console.log('Job completed successfully!'); break; case PublishingJobStatus.FAILED: console.log('Job failed:', job.publishErrorStatus); break; case PublishingJobStatus.CANCELLED: console.log('Job was cancelled'); break; } } checkPublishingJob().catch(console.error); ``` -------------------------------- ### Initialize AxiosHttpClient Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/HttpClient.md Shows how to create an instance of the default `AxiosHttpClient`, optionally providing Axios configuration such as timeouts and custom headers. ```typescript import { AxiosHttpClient } from 'dc-management-sdk-js'; const httpClient = new AxiosHttpClient({ timeout: 15000, headers: { 'User-Agent': 'MyApp/1.0' } }); ``` -------------------------------- ### Get Hierarchy Parents and Children Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/DynamicContent.md Retrieve the parent or children of a specific hierarchy item using its ID. Requires an initialized Dynamic Content client. ```typescript hierarchies: { parents: { get(id: string): Promise }, children: { get(id: string): Promise } } ``` ```typescript const parents = await client.hierarchies.parents.get('item-id-123'); const children = await client.hierarchies.children.get('item-id-123'); ``` -------------------------------- ### Handling 403 Forbidden Error Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/errors.md Provides an example for catching a 403 Forbidden error, which occurs when a user is authenticated but lacks the necessary permissions for a resource. ```typescript try { // User doesn't have access to this hub const hub = await client.hubs.get('hub-without-access'); } catch (err) { console.log('Status:', err.response?.status); // 403 } ``` ```typescript try { const hub = await client.hubs.get('hub-id'); } catch (err) { if (err instanceof HttpError && err.response?.status === 403) { console.error('Permission denied - contact administrator'); } } ``` -------------------------------- ### Initialize Client with Personal Access Token (PAT) Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/configuration.md Initialize the client using a Personal Access Token. This is recommended for backend services or CLI tools needing simple, static authentication. ```typescript const client = new DynamicContent({ patToken: 'your-personal-access-token' }); ``` -------------------------------- ### Manage Content Type Schema Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/ContentType.md Get or update the associated JSON schema document for a content type. This allows retrieval of the current schema or applying updates. ```typescript related.contentTypeSchema: { get(): Promise, update(mutation?: ContentTypeCachedSchema): Promise } ``` ```typescript // Get the cached schema const schema = await contentType.related.contentTypeSchema.get(); console.log('Schema:', schema.cachedSchema); // Update the schema const updatedSchema = new ContentTypeCachedSchema(); await contentType.related.contentTypeSchema.update(updatedSchema); ``` -------------------------------- ### Create Content Item via Repository Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/ContentItem.md Demonstrates how to create a new content item using a content repository. Requires defining the item's schema and body. ```typescript import { ContentItem } from 'dc-management-sdk-js'; const repo = await client.contentRepositories.get('repo-id'); const item = new ContentItem(); item.label = 'My Article'; item.body = { _meta: { schema: 'https://raw.githubusercontent.com/amplience/dc-content-types/master/text-block.json' }, text: 'Article content here...' }; const created = await repo.related.contentItems.create(item); console.log('Created item:', created.id, 'Version:', created.version); ``` -------------------------------- ### Create a Content Item Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/README.md This snippet demonstrates how to fetch a repository, define a new content item with its schema and body, and then create it within the repository. The item's label and body, including its schema, must be defined before creation. ```typescript const repo = await client.contentRepositories.get('repo-id'); const item = new ContentItem(); item.label = 'Article'; item.body = { _meta: { schema: 'https://example.com/schema.json' }, title: 'Title', content: 'Content' }; const created = await repo.related.contentItems.create(item); ``` -------------------------------- ### Create and List Extensions Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/Hub.md This snippet demonstrates how to create a new extension and list all extensions associated with a hub. ```typescript related.extensions: { create(resource: Extension): Promise, list(options?: Pageable): Promise> } ``` ```typescript const extension = new Extension(); extension.name = 'my-extension'; extension.label = 'My Extension'; extension.url = 'https://example.com/extension'; extension.category = 'CONTENT_FIELD'; const created = await hub.related.extensions.create(extension); const extensions = await hub.related.extensions.list(); ``` -------------------------------- ### Initialize Client with Custom API and Auth URLs Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/configuration.md Configure the client to use custom API and authentication URLs, typically for development, testing, or specific environments. ```typescript const client = new DynamicContent( { client_id, client_secret }, { apiUrl: 'https://custom.api.example.com/v2/content', authUrl: 'https://custom.auth.example.com' } ); ``` -------------------------------- ### Custom Authentication Header Provider Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/Authentication.md Implement the AuthHeaderProvider interface for custom authentication logic. This example shows fetching a token from a custom service and returning it in a Bearer format. ```typescript import { AuthHeaderProvider, DynamicContent, HalClient, DefaultHalClient, AxiosHttpClient } from 'dc-management-sdk-js'; class CustomAuthHeaderProvider implements AuthHeaderProvider { async getAuthHeader(): Promise { // Custom authentication logic const token = await fetchTokenFromCustomService(); return `Bearer ${token}`; } } // Use with client (requires manual setup) const httpClient = new AxiosHttpClient(); const authProvider = new CustomAuthHeaderProvider(); const halClient = new DefaultHalClient( 'https://api.amplience.net/v2/content', httpClient, authProvider ); // Note: DynamicContent doesn't expose this level of customization directly // You would need to extend DynamicContent or use the HalClient directly ``` -------------------------------- ### Importing SDK Types Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/types.md Demonstrates how to import various type definitions from the root 'dc-management-sdk-js' index file. ```typescript import { Status, Page, Pageable, ContentItem, // ... other types } from 'dc-management-sdk-js'; ``` -------------------------------- ### Handle 429 Too Many Requests Error Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/errors.md Illustrates catching a 429 error, which indicates that the rate limit has been exceeded. This example shows a basic loop that might trigger the error. ```typescript try { // Making too many rapid requests for (let i = 0; i < 1000; i++) { await client.contentItems.get(ids[i]); } } catch (err) { console.log('Status:', err.response?.status); // 429 } ``` -------------------------------- ### Create New Extension Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/Extension.md Illustrates the process of creating a new extension, including setting its core properties, adding snippets, and defining parameters as a JSON string. The extension is then created via its associated hub. ```typescript import { DynamicContent, Extension, Status, ExtensionSnippet } from 'dc-management-sdk-js'; async function createExtension() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); const hub = await client.hubs.get('hub-id'); const extension = new Extension(); extension.name = 'custom-field-editor'; extension.label = 'Custom Field Editor'; extension.description = 'A custom field editor for structured data'; extension.url = 'https://example.com/extensions/field-editor'; extension.category = 'CONTENT_FIELD'; extension.height = 400; extension.status = Status.ACTIVE; // Add snippets extension.snippets = [ { label: 'Example Usage', body: JSON.stringify({ type: 'object', properties: { title: { type: 'string' } } }) } ]; // Add parameters as JSON string extension.parameters = JSON.stringify({ color: 'blue', theme: 'light' }); const created = await hub.related.extensions.create(extension); console.log('Created extension:', created.id); } createExtension().catch(console.error); ``` -------------------------------- ### Initialize Client with Personal Access Token (PAT) Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/README.md A simpler authentication method suitable when manual token rotation is acceptable. Ensure your PAT_TOKEN environment variable is set. ```typescript const client = new DynamicContent({ patToken: process.env.PAT_TOKEN }); ``` -------------------------------- ### Publishing Workflow for Edition Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/api-reference/Edition.md Illustrates the steps involved in the publishing workflow for an edition, including checking status, validating slots, and scheduling. It also shows how to handle potential scheduling errors. ```typescript import { DynamicContent } from 'dc-management-sdk-js'; async function publishEdition() { const client = new DynamicContent({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, }); const edition = await client.editions.get('edition-id'); // Check publishing status console.log('Current status:', edition.publishingStatus); // Validate slots and content const slots = await edition.related.slots.list(); console.log(`Edition has ${slots.getItems().length} slots`); // Schedule the edition try { await edition.related.schedule(); console.log('Scheduled - status will move to SCHEDULED'); // Get updated edition to see new status const updated = await client.editions.get(edition.id); console.log('Updated status:', updated.publishingStatus); } catch (err) { console.error('Scheduling failed:', err); // Could retry with ignoreWarnings flag await edition.related.schedule(true); } } publishEdition().catch(console.error); ``` -------------------------------- ### Create Multiple Client Instances for Different Credentials Source: https://github.com/amplience/dc-management-sdk-js/blob/master/_autodocs/configuration.md When dealing with multiple sets of credentials, create separate client instances, each configured with its unique client ID and secret. This ensures proper authentication for different contexts. ```typescript const client1 = new DynamicContent({ client_id: process.env.CLIENT_ID_1, client_secret: process.env.CLIENT_SECRET_1 }); const client2 = new DynamicContent({ client_id: process.env.CLIENT_ID_2, client_secret: process.env.CLIENT_SECRET_2 }); ```