
CONTENTSTACK CMS Connector API Contentful

- производ: CMS Connector API – Contentful
- Опис: The migration-contentful package simplifies the process of migrating data from Contentful to Contentstack CMS by providing utility functions for extracting content types, mapping fields, and handling locales.
CMS Connector API – Contentful
This document outlines the functionalities and usage of the migration-contentful package, which is designed to simplify the process of migrating data from Contentful to Contentstack CMS. It provides key utility functions for extracting content types, mapping fields, and handling locales, ensuring a smooth and efficient migration process. The following sections detail the installation, available functions, and their specific behaviors.
migration-contentful Package
Готовоview
The migration-contentful package is used to simplify the process of migrating data from Contentful to Contentstack CMS. It helps with extracting content types, mapping fields, and handling locales. This package contains key utility functions to facilitate these tasks.
Инсталација
In your package.json, you reference this package from your local file system like this:
- ЈаваСцрипт
- “dependencies”: {
- “migration-contentful”: “file:migration-contentful”
- }
This makes the migration-contentful package available locally without the need to fetch it from an external registry like npm.
Кључне функције
You can import the following functions from the package to use in your project:
- extractContentTypes:
- This function extracts content types from the exported Contentful data and saves them locally.
- It processes the data to create a structured format that can be used for migration to another CMS. const { extractContentTypes } = require(‘migration-contentful’);
- createInitialMapper:
- Once the content types are extracted, this function transforms them into a mapping schema. This schema helps in migrating the data by ensuring fields are mapped correctly between systems. const { createInitialMapper } = require(‘migration-contentful’);
- extractLocale:
- This function extracts locale information (languages and region data) from Contentful exports. This is crucial for migrating content with language variations to the new CMS. const { extractLocale } = require(‘migration-contentful’);
Како користити
To use the functions in your code, simply import them like this:
- ЈаваСцрипт
- const { extractContentTypes, createInitialMapper, extractLocale } = require(‘migration-contentful’);
These functions will allow you to:
- Extract content types from a Contentful export.
- Create a field mapping based on the extracted data.
- Extract and manage locales for migrating language data
extractContentTypes Function
Готовоview
This module provides utilities to extract and save Contentful content type definitions along with their associated editor interfaces. The data is processed and saved as structured JSON files for use in CMS migration or synchronization pipelines.
Функција: extractContentTypes(filePath, prefix)
Опис
- Ако имате било каквих питања, обратите се tso-migration@contentstack.com.
- Чита а file containing Contentful content types and editor interfaces, processes them, and saves each content type in a structured format.
Параметри:
- fileПут (string): Path to the file containing the exported Contentful content model.
- префикс (string): Prefix to namespace or label the saved field definitions.
враћа:
Promise<void>: Resolves when content types are successfully processed and saved.
понашање:
- Checks if the folder at contentfulFolderPath exists. If not, it creates it.
- Reads the input file and extracts contentTypes and editorInterfaces.
- If contentTypes exist, it delegates processing to saveContentType(). Otherwise, it logs “No content-type found”.
Throws:
Logs and throws an error if reading the file or saving data fails.
Функција: saveContentType(contentTypes, editorInterface, prefix)
Опис:
Processes each content type and its fields by matching them with their respective editor controls and saves the data to JSON files.
Параметри:
- contentTypes (Array<Object>): Array of content type definitions.
- editorInterface (Array<Object>): Array of editor configurations for fields.
- prefix (string): Used to label field data.
враћа:
void: This function writes files and does not return anything.
понашање:
- Converts the sys.id of each content type into snake_case.
- Finds the matching editor interface by comparing content type IDs.
- Merges field definitions with their widget/editor info.
- Saves each content type as a prettified .json file in the target folder.
Излаз File
Each content type gets its own .json file named after its cleaned-up title (special characters removed, first letter capitalized).
Output Format (per field):
Each saved JSON array contains objects with the following keys:
- префикс
- contentUid
- contentDescription
- contentfulID
- id, name, type, localized, required, validations, disabled, omitted (from field definition)
- widgetId (from editor interface)
- contentNames (list of all content type IDs)
createInitialMapper Function
Готовоview
- The createInitialMapper function reads content model data exported from Contentful, transforms each model into a Contentstack-compatible schema format, and returns a complete mapping of content types.
- It is typically used during CMS migrations or synchronization processes between Contentful and Contentstack.
Потпис функције
- ЈаваСцрипт
- const createInitialMapper = async () => { … }
Инпутс
None were directly passed.
Чита fileс од:
- ЈаваСцрипт
- path.resolve(process.cwd(), `${config.data}/${config.contentful.contentful}`)
- where each file contains field definitions for a Contentful content type.
Излаз
An object in the following structure:
- ЈаваСцрипт
- contentTypes: [ … ] // array of content type mapping objects
Each contentType object contains:
| Поље | Тип | Опис |
|
статус |
број |
Indicates active state (1 = active) |
|
isUpdated |
боолеан |
Whether the mapping was updated |
|
updateAt |
стринг |
Тиместamp (left blank initially) |
|
otherCmsTitle |
стринг |
Content type title from Contentful |
|
otherCmsUid |
стринг |
UID from Contentful (contentfulID) |
|
contentstackTitle |
стринг |
Transformed title for Contentstack (Capitalized) |
|
contentstackUid |
стринг |
UID for Contentstack, corrected with uidCorrector() |
|
тип |
стринг |
Always ‘content_type’ |
| fieldMapping | низ | An array of field definitions, including system
поља |
Унутрашња логика
Читај Files
- ЈаваСцрипт
- конст files = await fs.readdir(…);
Gets all JSON files representing Contentful content types.
Iterate Files
- ЈаваСцрипт
- for (const file of files) { … }
За сваки file:
- Reads field definitions
- Derives content type title from fileиме
Build Schema Object
Each object includes:
- Metadata about the content type
- Default fields (title and url) added manually
- Custom fields generated via contentTypeMapper()
Generate Fields
- ЈаваСцрипт
- const contentstackFields = […uidTitle, …contentTypeMapper(data)].filter(Boolean);
- uidTitle: Hardcoded default fields for title and url
- contentTypeMapper(data): Dynamically maps Contentful fields to Contentstack schema
Delete Temporary Folder
- deleteFolderSync(path.resolve(…));
- Removes the data folder after processing to avoid re-use or conflicts.
Врати резултат
Returns the final list of mapped content types for further use.
Еррор Хандлинг
Any error during file reading, transformation, or folder deletion is caught and logged: js
CopyEdit
console.error(‘Error saving content type:’, error);
Example Return
- ЈаваСцрипт
- “contentTypes”: [
- “status”: 1,
- “isUpdated”: false,
- “updateAt”: “”,
- “otherCmsTitle”: “blogPost”,
- “otherCmsUid”: “blogPostID”,
- “contentstackTitle”: “BlogPost”, “contentstackUid”: “blog_post”, “type”: “content_type”,
- “fieldMapping”: [
- “uid”: “title”,
- “contentstackFieldType”: “text”, …
- },
- ...
Related Functions
- contentTypeMapper: Converts each Contentful field to Contentstack schema.
- uidCorrector: Normalizes field UIDs.
- extractAdvancedFields: Injects metadata (e.g., mandatory, unique).
- deleteFolderSync: Cleans up local temporary directories.
contentTypeMapper Function
Готовоview
The contentTypeMapper function is a comprehensive mapping utility that transforms a content model structure (typically from a CMS like Contentful) into a schema array suitable for another CMS (like Contentstack). Here’s a breakdown of how it works and what each section does — suitable for use in developer documentation:
Function Purpose
The contentTypeMapper function takes an array of content field definitions (data) and returns a normalized array of schema objects formatted for Contentstack. It supports various field types, widget configurations, and advanced metadata.
Потпис функције
- ЈаваСцрипт
- const contentTypeMapper = (data) => { … };
- Улаз: data – An array of field definition objects, typically exported from a CMS source.
- Излаз: schemaArray – An array of transformed field objects structured for Contentstack.
Core Logic (How it Works)
Iterate Through Input Data
- data.reduce((acc, item) => { … }, []);
- Each field (item) in the data array is processed based on its type and widgetId.
- Ако имате било каквих питања, обратите се tso-migration@contentstack.com.
Handle Different Field Types
- Богат текст
- Calls arrangeRte to resolve references.
- Uses createFieldObject with json type.
- Symbol, Text
- Handles widgets like singleLine, urlEditor, slugEditor, multipleLine, markdown, dropdown, radio, tagEditor, and listInput.
- Number, Integer
- Maps editors to number, or re-maps to dropdownNumber, radioNumber, etc.
- Датум
- Mapped directly to isodate.
- Array, Link
- Assets (Images, Files): Mapped to file, with .multiple = true if it’s an array.
- Entries (References):
- Parses linkContentType from validations.
- Derives references (referenceFields) using helper logic.
- Uses createFieldObject with reference type.
- Поље за потврду, Tag Editor, List Input: Mapped appropriately.
- Боолеан
- Mapped to boolean.
- Објекат
- If widgetId is an objectEditor, marked as app type.
- Otherwise, enriches the name using app metadata from appDetails.
- Локација
Creates a group field plus subfields for lat and lon.
Helper Function: createFieldObject
This standardizes the schema field output:
- ЈаваСцрипт
- {
- uid,
- otherCmsField
- otherCmsType,
- contentstackField,
- contentstackFieldUid,
- contentstackFieldType,
- backupFieldType,
- backupFieldUid,
- напредно
Where advanced comes from extractAdvancedFields, providing details like:
- обавезна
- јединствени
- nonLocalizable
- referenceFields (when applicable)
Special Logic
- uidCorrector() is used to standardize IDs for compatibility.
- Conditional checks on item.items, validations, and widgetId ensure the mapper handles deeply nested or loosely structured fields gracefully.
- References are deduplicated and capped for performance (slice(0, 9) or length < 25).
Console Logging
For widgets like tagEditor or listInput, a console.info() is called — likely for debugging purposes.
Резиме
This function is critical in migrating or transforming content model definitions from one CMS to another. It ensures:
- Widget-specific logic is respected
- Reference relationships are preserved
- Fields are enriched with necessary metadata
- Complex widgets like Location, Object, and Reference are handled correctly
extractLocale Function
Опис
This function extracts unique locale codes (e.g., en-us, fr-fr) from a Contentful JSON export and returns them in an array. These locale codes are later pushed to the database via a backend API to support localization in a new CMS like Contentstack.
Зависности
- јсонFileПутања: Path to the exported JSON file from Contentful.
- fs (Node.js built-in): Used to read the file садржаја.
Function: extractLocale
Сврха
- Extracts and returns a list of unique locale codes used in the legacy CMS. Parameters
- јсонFilePath (string) – File path to the exported Contentful data (JSON format).
Повратак
Array<string> – A list of unique locale codes.
Exampле:
- ЈаваСцрипт
- [‘en-us’, ‘fr-fr’]
- Returns an empty array [] if:
- No locales are found.
- Тхе file is missing or invalid.
Понашање
- Потврђује file path and JSON structure.
- Parses the JSON and extracts values from the locales array.
- Collects unique locale codes (locale.code).
- Handles and logs errors gracefully.
Exampле Усаге
- ЈаваСцрипт
- const extractLocale = require(‘./libs/extractLocale’);
- (async () => {
- const locales = await extractLocale(‘./legacy-export.json’); console.log(‘Locales found:’, locales);
- })();
Validator Contentful
Готовоview
The Contentful Validator verifies that a JSON content model exported from Contentful contains all required properties as defined in a configuration schema (contentful.json). It is used as a pre-validation step before transforming or migrating content models into another CMS like Contentstack.
Function: contentfulValidator(data: string)
Опис:
Validates a raw JSON string exported from Contentful against a required schema definition provided in contentful.json.
Параметри: data (string): Raw JSON content model as a string (from Contentful)
враћа:
- true if:
All required properties listed in the config are present in the parsed JSON object. - false if:
Any required property is missing. - The JSON is malformed or cannot be parsed.
Унутрашња логика
- Parse the JSON input
- ЈаваСцрипт
- jsonData = JSON.parse(data);
- Attempts to parse the input string into a valid JavaScript object.
- If parsing fails, the function returns false.
- Iterate Over Config Schema
- ЈаваСцрипт
- Object.values(jsonConfig).every((prop: any) => { … });
- Loops through each field defined in the contentful.json schema.
- Validate Each Property
- ЈаваСцрипт
- if (jsonData?.hasOwnProperty(prop?.name)) {
- ретурн труе;
- }
- else if (prop?.required === ‘true’) {
- ретурн фалсе;
- }
- ретурн труе;
- Checks if the required properties exist in the parsed jsonData.
- If a required property is missing, the function short-circuits and returns false.
- Еррор Хандлинг
ЈаваСцрипт
try { … } catch (error) {
ретурн фалсе;- The function handles all parsing or runtime errors.
- If parsing fails or unexpected data structures are encountered, false is returned without throwing.
Exampле Усаге
- ЈаваСцрипт
- import contentfulValidator from ‘./validators/contentful-validator’;
- import fs from ‘fs’;
- const rawData = fs.readFileSync(‘contentful-export.json’, ‘utf-8’);
- if (contentfulValidator(rawData)) {
- console.log(‘✅ Contentful schema is valid!’);
- } остало {
- console.error(‘❌ Invalid schema: Missing required fields or bad JSON.’);
Running the upload-api Project on Any Operating System
- The following instructions will guide you in running the upload-api folder on any operating system, including Windows and macOS.
- Ако имате било каквих питања, обратите се tso-migration@contentstack.com.
Starting the upload-api Project
- There are two methods to start the upload-api project: Method 1:
- Run the following command from the root directory of your project:
- Схелл
- npm run upload
- This command will directly start the upload-api package.
2. метод:
Navigate to the upload-api directory manually and run the development server:
- Схелл
- cd upload-api
- npm run start
This approach starts the upload-api from within its own directory.
Restarting After Termination
If the project terminates unexpectedly, you can restart it by following the same steps outlined above. Choose either Method 1 or Method 2 to relaunch the service.
Ограничења
- Not handle the use case of deletion of existing destination stack in runtime
- Content mapper module | existing stack | existing content type mapped | Modular blocks, taxonomy these fields can be matched with Single Line Textbox field
- Content Type Migration Limitations in Test Stacks
When migrating content types in a test stack, the handling of attached references depends on your organization’s reference limit:- Organizations with a reference limit of 50: Full data migration is supported if a content type has more than 10 references.
- Organizations with a reference limit of 10: If a content type has more than 10 references, only the ‘title’ and ‘URL’ fields will be migrated.
- Проблем: Data migration may encounter unforeseen problems if the Contentful data contains duplicate UIDs.
Ако имате било каквих питања, обратите се tso-migration@contentstack.com.
ФАК
What is the purpose of the migration-contentful package?
How do I install the migration-contentful package?
What functions are available in the migration-contentful package?
Документи / Ресурси
![]() | CMS Connector API Contentful |
Референце
- console.infoconsole.info
- mailto:tso-migration@contentstack.comcontentstack.com
- docs.google.com/document/d/11M9OUyaAO5eu3Wt-V5hhLzis7ExFhdhJqG-4XY4aOHs/edit?tab=t.32gbkd7ckhmmдоцс.гоогле.цом
- docs.google.com/document/d/11M9OUyaAO5eu3Wt-V5hhLzis7ExFhdhJqG-4XY4aOHs/edit?tab=t.p841gsd3pqnnдоцс.гоогле.цом
- docs.google.com/document/d/11M9OUyaAO5eu3Wt-V5hhLzis7ExFhdhJqG-4XY4aOHs/edit?tab=t.vzy8zuqlem8yдоцс.гоогле.цом
- sys.id :: web services fulfilment hubsys.id
- Упутство за употребуmanual.tools
