Last active
April 10, 2025 15:45
-
-
Save shanonplace/12b6cccaa76b4a3287072c57cc35d83b to your computer and use it in GitHub Desktop.
Example script to copy a workflow definition from one environment to another in Contentful.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as dotenv from "dotenv"; | |
import fetch from "node-fetch"; | |
dotenv.config(); | |
const workflowId = "3THnDj08TlJBoAM5oJorrrrfWn"; //These three could be .env file strings or cli params | |
const originEnvironment = "Workflow-Test"; | |
const destinationEnvironment = "master"; | |
//get a workflow definition from the origin environment | |
const workflowJson = await getWorkflowDefinition(workflowId, originEnvironment); | |
console.log("copying workflow ", JSON.stringify(workflowJson, null, 2)); | |
//clear out the sys and id fields from the original workflow definition, as they cannot be included in a create | |
delete workflowJson.sys; | |
workflowJson.steps.forEach((s) => { | |
delete s.id; | |
}); | |
//now create a new workflow in the destination environment | |
const createResponse = await createWorkflow( | |
workflowJson, | |
destinationEnvironment | |
).catch((e) => { | |
console.log("error is ", JSON.stringify(e)); | |
}); | |
console.log("Workflow Created! ", JSON.stringify(createResponse, null, 2)); | |
//***********functions***************// | |
//get the full workflow definition to get a list of steps ids | |
async function getWorkflowDefinition(workflowId, environment) { | |
const token = `Bearer ${process.env.CMA_TOKEN}`; | |
const workflowFetchUrl = `https://api.contentful.com/spaces/${process.env.SPACE_ID}/environments/${environment}/workflow_definitions/${workflowId}`; | |
const workflowRes = await fetch(workflowFetchUrl, { | |
headers: { | |
Authorization: token, | |
}, | |
}); | |
const workflow = await workflowRes.json(); | |
return workflow; | |
} | |
//async function to create workflow | |
async function createWorkflow(workflowJson, environment) { | |
const token = `Bearer ${process.env.CMA_TOKEN}`; | |
const workflowCreateUrl = `https://api.contentful.com/spaces/${process.env.SPACE_ID}/environments/${environment}/workflow_definitions`; | |
const workflowRes = await fetch(workflowCreateUrl, { | |
headers: { | |
"Authorization": token, | |
"Content-Type": "application/vnd.contentful.management.v1+json", | |
"Accept": "application/json, text/plain, */*", | |
}, | |
method: "POST", | |
body: JSON.stringify(workflowJson), | |
}); | |
const workflow = await workflowRes.json(); | |
return workflow; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uses a .env file with the following format: