Contentful logo

Contentful Community

Using Management API from migration API

Hello everyone.
How would one go about using Management API from within migration CLI scripts?
I currently have the following script:
module.exports = function(migration) {
const robotsType = migration.createContentType(‘robots’).name(‘Robots’).description(‘robots’);
}

Let’s say i want to add a new default entry, as part of this migration, but the migration API doesn’t support it. Ideally we would need access to a management API object, from within here, but in order for that to be possible, we need a spaceId and a management token to be accessible from within the above function. How could we make this work?

Hey @aldub,

you’re right, we don’t offer that right out of the box currently.

I explained the general approach in a different thread here with regards to assets: Migrating values between locales

As said there the migration function can be async (as transformEntryForLocale):

module.exports = async function (migration) { ... }

For the space ID and access token you’d use something like yargs to parse them out of the process.argv. If you’re using an env var for the access token you could read it from process.env.CONTENTFUL_MANAGEMENT_ACCESS_TOKEN

Maybe that’s already enough for you to start? If you want a more detailed explanation I’m happy to help you out there :slight_smile:

1 Like

FYI: We would rather see the initialized space accessible thru the migration object somehow, but the workaround via environment variables will work for the time being.

Another issue is that it seems like you cannot JUST add management API code to the end of migration API code, because it executes immediately. So we are currently forced to have our custom code in a separate migration file instead of extending an existing one.

So I guess what would be helpful here is some sort of concept of a pre and post hook.
Pre is already possible by just writing it as part of the migration, but you’re correct that it’s not easy to execute something after a migration as part of the migration file. That’s definitely a good suggestion for an improvement.

Hey guys, any updates on this?