Using async with contentful-management to List and Create Entries
I recently experimented with the JavaScript SDK for contentful-management and wanted to jot down my findings before I forget.
Preparation
Create a Contentful account and space. This article helped me understand the process clearly.
Install the necessary packages for your Node.js project:
npm install dotenv
npm install contentful-management
Create a .env file in the same directory as your package.json and add the following:
personal_access_token=your_personal_access_token
space_id=your_space_id
environment_id=your_environment_id_or_master
You need to create a Personal Access Token specifically for the Contentful Management API, separate from the Delivery and Preview API keys. For details, check the official page.
Retrieving a List of Entries from Contentful
In Contentful, each piece of data is called an entry, similar to a record in a relational database.
Here's the source code to obtain a list of entries:
require('dotenv').config()
const env = process.env
process.on('unhandledRejection', console.dir);
const contentful = require('contentful-management')
const client = contentful.createClient({
accessToken: env.personal_access_token
});
(async () => {
const space = await client.getSpace(env.space_id);
const environment = await space.getEnvironment(env.environment_id);
const entries = await environment.getEntries();
entries.items.forEach(item => console.log(item));
})();
Registering an Entry in Contentful
A content model in Contentful is akin to a table in a database. We will create a new entry in this model. First, create it as a draft, and then publish it.
Here's the source code:
The fields section varies depending on your content model, so adjust as necessary. If you've changed Contentful's Settings > Locales to ja, replace en-US with ja.
require('dotenv').config()
const env = process.env
process.on('unhandledRejection', console.dir);
const contentful = require('contentful-management')
const client = contentful.createClient({
accessToken: env.personal_access_token
});
(async () => {
const space = await client.getSpace(env.space_id);
const environment = await space.getEnvironment(env.environment_id);
const draftEntry = await environment.createEntry('hoge_content_type', {
fields: {
id: {
'en-US': 'hoge_id'
},
name: {
'en-US': 'hoge_name'
}
}
});
try {
const publishedEntry = await draftEntry.publish();
console.log(`Published entry ID: ${publishedEntry.sys.id}`);
} catch (err) {
console.error(err);
}
})();
Remember to change 'hoge_content_type' to your content model's ID as needed.
In Conclusion
I referred to the following pages when creating this article. Many thanks for the clear information.
Top comments (0)