Manage Contentful Models with Migration Script

Use transformEntriesToType and transformEntries to apply automatic and predictable content migration

Photo by Jessy Paston on Unsplash

Install and configure the Contentful CLI and the environment

npm install -g contentful-cli
export SPACE_ID=my-space-id contentful space use --space-id $SPACE_ID
contentful space environment create --environment-id 'dev' --name 'Development'
https://www.contentful.com/faq/environments/

Write migration script

const uuid62 = require("uuid62");
//Contentful uses uuid behind the scene to create the contentful_id //field which we would need for the identity key below
module.exports = (migration) => {
// a customised function to create new EntryTitle
function getNewEntryTitle(oldEntryTitle) {
let list = oldEntryTitle.split("/");
list.splice(0, 1, "typeA");
list.push("typeB-typeA");
return list.join("/");
}

migration.transformEntriesToType({
sourceContentType: "B",
targetContentType: "A",
from: ["entryTitle", "name", "age", "title"],
shouldPublish: "preserve",
updateReferences: true,
removeOldEntries: true,
identityKey: function(fromFields) {
if (!fromFields) {
return;
}
const id = uuid62.v4();
return id;
},
transformEntryForLocale: function(fromFields, currentLocale) {
if (!fromFields || currentLocale !== "en-US") {
return;
}

return {
entryTitle: !fromFields.entryTitle
? undefined
: getNewEntryTitle(fromFields.entryTitle[currentLocale]),
name: !fromFields.name ? undefined : fromFields.name[currentLocale],
age: !fromFields.age ? undefined : fromFields.age[currentLocale],
title: !fromFields.title ? undefined : fromFields.title[currentLocale],
status: undefined
};
},
});

migration.transformEntries({
contentType: "C",
from: ["Bb"],
to: ["Aa"],
shouldPublish: "preserve",
transformEntryForLocale: function(fromFields, currentLocale) {
if (!fromFields || currentLocale !== "en-US") {
return;
}

return {
Aa: !fromFields.Bb
? undefined
: fromFields.Bb[currentLocale],
};
},
});

const cc = migration.editContentType("C");
cc.deleteField("Bb");

migration.deleteContentType("B");
};

Run the script using the CLI

contentful space migration — environment-id ‘dev’ migrations/script_1.js
Environment: devMigrate entries from B
- from: B
- to: A
? Do you want to apply the migration Yes
✔ Migrate entries from B
Transform entries for C
— from: Bb
— to: Aa
? Do you want to apply the migration Yes
❯ Transform entries for C
✔ Transform entries for C
Update Content Type CDelete field BbPublish Content Type C
? Do you want to apply the migration Yes
✔ Update Content Type C
🎉 Migration successful

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store