{"id":15459170,"url":"https://github.com/atidatech/contentful-lib-helpers","last_synced_at":"2026-03-02T10:31:00.429Z","repository":{"id":153047403,"uuid":"612291498","full_name":"AtidaTech/contentful-lib-helpers","owner":"AtidaTech","description":"Contentful CMA Helper Library","archived":false,"fork":false,"pushed_at":"2024-08-27T09:20:13.000Z","size":388,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-10-18T19:32:09.529Z","etag":null,"topics":["contentful","contentful-js-sdk","contentful-management","helper-functions","javascript","nodejs","npm"],"latest_commit_sha":null,"homepage":"https://npmjs.com/package/contentful-lib-helpers","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/AtidaTech.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-03-10T16:02:09.000Z","updated_at":"2024-08-27T09:18:58.000Z","dependencies_parsed_at":null,"dependency_job_id":"584f535a-087e-4361-b863-0967e10701b3","html_url":"https://github.com/AtidaTech/contentful-lib-helpers","commit_stats":null,"previous_names":[],"tags_count":19,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AtidaTech%2Fcontentful-lib-helpers","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AtidaTech%2Fcontentful-lib-helpers/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AtidaTech%2Fcontentful-lib-helpers/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AtidaTech%2Fcontentful-lib-helpers/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AtidaTech","download_url":"https://codeload.github.com/AtidaTech/contentful-lib-helpers/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249259146,"owners_count":21239422,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["contentful","contentful-js-sdk","contentful-management","helper-functions","javascript","nodejs","npm"],"created_at":"2024-10-01T23:05:12.665Z","updated_at":"2025-04-16T16:31:51.210Z","avatar_url":"https://github.com/AtidaTech.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![License: MIT](https://img.shields.io/github/license/AtidaTech/contentful-lib-helpers)](https://opensource.org/licenses/MIT)\n[![npm](https://img.shields.io/npm/v/contentful-lib-helpers)](https://npmjs.com/package/contentful-lib-helpers)\n![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/AtidaTech/contentful-lib-helpers)\n![Downloads](https://img.shields.io/npm/dw/contentful-lib-helpers)\n![Forks](https://img.shields.io/github/forks/AtidaTech/contentful-lib-helpers)\n[![Bun.sh](https://img.shields.io/badge/bun.sh-compatible-orange)](https://bun.sh)\n\n\u003cp align=\"center\"\u003e\n\n# ![Contentful Lib Helpers](./images/logo-helpers-100.png)\n\n\u003c/p\u003e\n\n# Contentful CMA Helper Library\n\nA utility library for the [Contentful Management API 🔗](https://github.com/contentful/contentful-management.js), designed to help developers interact with the API in a more intuitive and streamlined way. This library provides functions for common tasks, such as retrieving and publishing entries, as well as tools for handling errors and logging.\n\n\u003ch3\u003eSponsored by \u003ca href=\"https://github.com/AtidaTech\"\u003e\u003cb\u003eAtida\u003c/b\u003e \u003cimg src=\"https://avatars.githubusercontent.com/u/127305035?s=200\u0026v=4\" width=\"14px;\" alt=\"Atida\" /\u003e\u003c/a\u003e\u003c/h3\u003e\n\n\u003chr /\u003e\n\n[✨ Features](#-features) · [💡 Installation](#-installation) · [📟 Example](#-example) · [🎹 Usage](#-usage) · [🔊 verbosityLevel](#-verbositylevel) · [📅 ToDo](#-todo) · [👾 Contributors](#-contributors) · [🎩 Acknowledgments](#-acknowledgements) · [📚 Collection](#-other-scripts-in-the-same-collection) · [📄 License](#-license)\n\n\u003chr /\u003e\n\n\n## ✨ Features\n- Easy-to-use functions for common tasks\n- Compatible return types with CMA\n- Customizable verbosity level for console logging\n- Robust error handling and validation\n- Async/await API for easy integration into async workflows\n\n## 💡 Installation\n\nTo use this helper library, you must have [NodeJS 🔗](https://nodejs.org/) and [npm 🔗](http://npmjs.org) installed. \n\nTo install it, simply run:\n\n```shell\nnpm install contentful-lib-helpers --save\n```\n\nOr, if using [yarn 🔗](https://yarnpkg.com/lang/en/):\n\n```shell\nyarn add contentful-lib-helpers\n```\n\n\u003e Similarly, if you are using [Bun 🔗](https://bun.sh), just run\u003cbr /\u003e`bun add contentful-lib-helpers`\n\n### Requirements\n\n* `node` \u003e= 18.20.0\n* `npm` \u003e= 10.5.0\n* `contentful-management` \u003e= 11.31.7\n\n## 📟 Example\n\nHere a simple example of writing a function that finds an entry by slug, add a tag and then republishes it.\u003cbr /\u003e\nWe show both implementations: one using only the Contentful Management SDK and the other one, much shorter, using the Contentful Lib Helpers.\n\n\u003cdetails open=\"open\"\u003e\n\u003csummary\u003eWith Contentful Lib Helpers\u003c/summary\u003e\n\n```javascript\n(async function main () {\n    const contentfulManagement = require('contentful-management')\n    const lib = await import('contentful-lib-helpers')\n    const environment = await lib.getEnvironment(\n        contentfulManagement,\n        'your-access-token',\n        'your-space-id',\n        'master'\n    )\n\n    const entryId = await lib.getEntryIdByUniqueField(\n        environment,\n        'page',\n        'slug',\n        '/my-awesome-blog-post'\n    )\n\n    if (entryId) {\n        await lib.addEntryTag(environment, entryId, 'your-tag')\n        await lib.publishEntry(environment, entryId)\n    }\n})()\n```\n\n\u003c/details\u003e\n\n\n\u003cdetails\u003e\n  \u003csummary\u003eOnly with Contentful Management SDK\u003c/summary\u003e\n\n```javascript\n(async function main () {\n    const contentfulManagement = require('contentful-management')\n    const client = await contentfulManagement.createClient({\n    accessToken: 'your-access-token',\n    })\n\n    try {\n        // Get the environment\n        const space = await client.getSpace('your-space-id')\n        const environment = await space.getEnvironment('master')\n\n        // Get the entry ID by unique field\n        const entry = await environment.getEntries({\n            content_type: 'page',\n            ['fields.slug']: '/my-awesome-blog-post',\n            limit: 1\n        })\n\n        const entryId = entry.items.length \u003e 0 ? entry.items[0].sys.id : null\n\n        if (entryId) {\n            // Add tag to the entry\n            const tagName = 'country-it'\n            const entryWithTags = await environment.getEntry(entryId).then((entry) =\u003e {\n                entry.metadata = entry.metadata || { tags: [] }\n                if (!entry.metadata.tags.includes(tagName)) {\n                    entry.metadata.tags.push({\n                        sys: {\n                            type: 'Link',\n                            linkType: 'Tag',\n                            id: tagName\n                        }\n                    })\n                }\n                return entry\n            })\n            await entryWithTags.update()\n\n            // Publish the entry with tag\n            const publishedEntry = await environment.getEntry(entryId).then((entry) =\u003e {\n                entry.metadata = entry.metadata || {}\n                entry.metadata.tags = entry.metadata.tags || []\n                return entry.publish()\n            })\n\n            console.log(`Published entry with ID ${publishedEntry.sys.id} and tag ${tagName}`)\n        } else {\n            console.error(`Entry not found`)\n        }\n    } catch (error) {\n        console.error(`Error: ${error.message}`)\n    }\n})()\n```\n\n\u003c/details\u003e\n\n### Note\nTwo alternative ways to include the Contentful library as ES Module are the following:\n\n```js\n// At the beginning of the file\nimport contentfulManagement from 'contentful-management'\n\n// Inside a function\nconst { default: contentfulManagement } = await import('contentful-management')\n\n// If you are using Bun.sh\nconst contentfulManagement = await import('contentful-management')\n```\n\nSee also: [NodeJS modules import 🔗](https://reflectoring.io/nodejs-modules-imports/)\n\n## 🎹 Usage\nHere are the methods available in this library and how to use them:\n\n**Space/Environment**\n\n* [getSpace](#-getspace)\n* [getEnvironment](#-getenvironment)\n* [deleteEnvironment](#-deleteenvironment)\n\n**Content-types/Entries**\n\n* [getContentTypes](#-getcontenttypes)\n* [getContentType](#-getcontenttype)\n* [getAllEntriesByContentType](#-getallentriesbycontenttype)\n* [getEntryIdByUniqueField](#-getentryidbyuniquefield)\n* [getEntry](#-getentry)\n* [extractStatusFromSys](#-extractstatusfromsys)\n* [publishEntry](#-publishentry)\n* [unpublishEntry](#-unpublishentry)\n\n**Tags**\n\n* [getTagExists](#-gettagexists)\n* [addEntryTag](#-addentrytag)\n* [removeEntryTag](#-removeentrytag)\n\n**Locales**\n\n* [getAllLocales](#-getalllocales)\n* [getAllLocalesCode](#-getalllocalescode)\n* [getDefaultLocale](#-getdefaultlocale)\n* [getDefaultLocaleCode](#-getdefaultlocalecode)\n* [getDefaultValuesForLocales](#-getdefaultvaluesforlocales)\n\n**Release**\n\n* [duplicateEnvironment](#-duplicateenvironment)\n* [enableCdaKey](#-enablecdakey)\n* [linkAliasToEnvironment](#-linkaliastoenvironment)\n* [syncScheduledActions](#-syncscheduledactions)\n\n\u003chr /\u003e\n\n### • `getSpace`\n\nThe function retrieves a Contentful space object by its ID, using the Contentful Management API.\n\n#### Parameters\n- `contentfulManagement` - The Contentful Management library.\n- `contentfulToken` - The Contentful access token.\n- `contentfulSpaceId` - The ID of the space to retrieve.\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\nThe function returns a Promise that resolves with the Space object, or null if not found.\n\n#### Example Usage\n\n```javascript\nimport { getSpace } from 'contentful-lib-helpers'\nimport contentfulManagement from 'contentful-management'\nconst contentfulToken = 'your-access-token'\nconst contentfulSpaceId = 'your-space-id'\n\nconst space = await getSpace(\n    contentfulManagement, \n    contentfulToken, \n    contentfulSpaceId, \n    2\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(space)\u003c/code\u003e\u003c/summary\u003e\n\n```js\n{\n  name: 'Contentful Test Space',\n  sys: {\n    type: 'Space',\n    id: 'your-space-id',\n    version: 2,\n    createdBy: { sys: [Object] },\n    createdAt: '2023-03-31T10:41:25Z',\n    updatedBy: { sys: [Object] },\n    updatedAt: '2023-03-31T10:42:41Z',\n    organization: { sys: [Object] }\n  }\n}\n```\n\n\u003c/details\u003e\n\n\u003chr /\u003e\n\n### • `getEnvironment`\n\nThe function retrieves a Contentful environment object by ID, using the Contentful Management API.\n\n#### Parameters\n- `contentfulManagement` - The Contentful Management library.\n- `contentfulToken` - The Contentful access token.\n- `contentfulSpaceId` - The ID of the space to retrieve.\n- `contentfulEnvironmentId` - The ID of the environment to retrieve (default `master`).\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\nThe function returns a Promise that resolves with the Environment object, or null if not found.\n\n#### Example Usage\n\n```javascript\nimport { getEnvironment } from 'contentful-lib-helpers'\nimport contentfulManagement from 'contentful-management'\nconst contentfulToken = 'your-access-token'\nconst contentfulSpaceId = 'your-space-id'\nconst contentfulEnvironmentId = 'your-environment-id'\n\nconst environment = await getEnvironment(\n    contentfulManagement, \n    contentfulToken, \n    contentfulSpaceId,\n    contentfulEnvironmentId,\n    2\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(environment)\u003c/code\u003e\u003c/summary\u003e\n\n```js\n{\n  name: 'master',\n  sys: {\n    type: 'Environment',\n    id: 'master',\n    version: 3,\n    space: { sys: [Object] },\n    status: { sys: [Object] },\n    createdBy: { sys: [Object] },\n    createdAt: '2023-04-04T15:13:55Z',\n    updatedBy: { sys: [Object] },\n    updatedAt: '2023-04-04T15:13:56Z',\n    aliases: []\n  }\n}\n```\n\u003c/details\u003e\n\n\u003chr /\u003e\n\n### • `getContentTypes`\n\nThe function retrieves get all Content-types in a Contentful environment.\n\n#### Parameters\n- `environment` - Environment Object (you can retrieve it with [getEnvironment](#-getenvironment)).\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\nThe function returns a Promise that resolves with a Content-type collection if successful, or an empty Collection otherwise.\n\nNote: the decision to return an empty collection, is because collections of any kind are usually looped trough. If we would be returning a `null`/`false` value, that would need to be verified before looping through the elements. With the empty collection, the items can be passed to the loop (that won't loop because empty).\n\n#### Example Usage\n\n```javascript\nconst allContentTypes = await getContentTypes(\n    environment, \n    2\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(allContentTypes)\u003c/code\u003e\u003c/summary\u003e\n\n```js\n{\n  sys: { type: 'Array' },\n  total: 3,\n  skip: 0,\n  limit: 100,\n  items: [\n    {\n      sys: [Object],\n      displayField: 'key',\n      name: 'Translation',\n      description: '',\n      fields: [Array]\n    },\n    {\n      ...\n    },\n    {\n      ...\n    }\n  ]\n}\n```\n\u003c/details\u003e\n\n\u003chr /\u003e\n\n### • `getContentType`\n\nThe function retrieves a Content-type object by its ID.\n\n#### Parameters\n- `environment` - Environment Object (you can retrieve it with [getEnvironment](#-getenvironment)).\n- `contentTypeId` - The ID of the content-type to retrieve.\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\n\nThe function returns a Promise that resolves with the content-type object if it exists, or `null` otherwise.\n\n#### Example Usage\n\n```javascript\nconst contentType = await getContentTypes(\n    environment, \n    'translation',\n    2\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(contentType)\u003c/code\u003e\u003c/summary\u003e\n\n```js\n{\n  sys: {\n    space: { sys: [Object] },\n    id: 'translation',\n    type: 'ContentType',\n    createdAt: '2023-03-31T11:12:04.950Z',\n    updatedAt: '2023-03-31T11:18:19.563Z',\n    environment: { sys: [Object] },\n    publishedVersion: 13,\n    publishedAt: '2023-03-31T11:18:19.563Z',\n    firstPublishedAt: '2023-03-31T11:12:05.422Z',\n    createdBy: { sys: [Object] },\n    updatedBy: { sys: [Object] },\n    publishedCounter: 7,\n    version: 14,\n    publishedBy: { sys: [Object] }\n  },\n  displayField: 'key',\n  name: 'Translation',\n  description: '',\n  fields: [\n    {\n      id: 'key',\n      name: 'key',\n      type: 'Symbol',\n      localized: false,\n      required: true,\n      validations: [Array],\n      disabled: false,\n      omitted: false\n    },\n    {\n      id: 'value',\n      name: 'value',\n      type: 'Symbol',\n      localized: true,\n      required: true,\n      validations: [],\n      disabled: false,\n      omitted: false\n    }\n  ]\n}\n```\n\u003c/details\u003e\n\n\u003chr /\u003e\n\n### • `getAllEntriesByContentType`\n\nIt gets a Collection of all the Contentful Entries, by Content-type. The peculiarity of this method is that does the pagination (default 1000 elements) for you, and the returned collection contains all the entries.\n\n#### Parameters\n- `environment` - Environment Object (you can retrieve it with [getEnvironment](#-getenvironment)).\n- `contentTypeId` - The ID of the content-type to retrieve.\n- `limit` - Number of entries to retrieve at each loop. Default `1000`.\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\n\nThe function returns a Promise that resolves with a Collection of Contentful Entries, or an empty Collection otherwise. \n\nNote: the decision to return an empty collection, is because collections of any kind are usually looped trough. If we returned a `null`/`false` value, that would need to be verified before looping through the elements. With the empty collection, the items can be passed to the loop (that won't loop because empty).\n\n\n#### Example Usage\n\n```javascript\nconst allEntries = await getAllEntriesByContentType(\n    environment, \n    'translation',\n    1000,\n    2\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(allEntries)\u003c/code\u003e\u003c/summary\u003e\n\n```js\n{\n  sys: { type: 'Array' },\n  total: 5,\n  skip: 0,\n  limit: 5,\n  items: [\n    { metadata: [Object], sys: [Object], fields: [Object] },\n    { metadata: [Object], sys: [Object], fields: [Object] },\n    { metadata: [Object], sys: [Object], fields: [Object] },\n    { metadata: [Object], sys: [Object], fields: [Object] },\n    { metadata: [Object], sys: [Object], fields: [Object] }\n  ]\n}\n```\n\u003c/details\u003e\n\n\u003chr /\u003e\n\n### • `getEntryIdByUniqueField`\n\nFind an Entry in a specific Content Type and locale by its unique identifier field.\n\n#### Parameters\n- `environment` - Environment Object (you can retrieve it with [getEnvironment](#-getenvironment)).\n- `fieldId` - The ID of the unique field to search for. A unique field is usually a mandatory and unique field in the Content-type (ie: slug).\n- `fieldValue` - The value to search for in the unique field.\n- `fieldLocale` - The locale to search in for the unique field. If not provided, the default locale will be used.\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\n\nA Promise that resolves to the Entry ID or `null` otherwise. We can then use [getEntry](#-getentry) to retrieve the Entry itself.\n\n#### Example Usage\n\n```javascript\nconst entryId = await getEntryIdByUniqueField(\n    environment,\n    'translation',\n    'key',\n    'test.entry'\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(entryId)\u003c/code\u003e\u003c/summary\u003e\n\n```\nAKjzIrXfTQFS6oXjJp71Z\n```\n\u003c/details\u003e\n\u003chr /\u003e\n\n### • `getEntry`\n\nGet a Contentful entry by ID.\n\n#### Parameters\n- `environment` - Environment Object (you can retrieve it with [getEnvironment](#-getenvironment)).\n- `entryId` - The ID of the entry to get.\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\n\nA Promise that resolves with the entry object, or `null` if not found.\n\n#### Example Usage\n\n```javascript\nconst entry = await getEntry(\n    environment,\n    'exampleEntryId',\n    2\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(entry)\u003c/code\u003e\u003c/summary\u003e\n\n```js\n{\n  metadata: { tags: [] },\n  sys: {\n    space: { sys: [Object] },\n    id: 'GKjzIfXfTQFS8oXjJp71Y',\n    type: 'Entry',\n    createdAt: '2023-04-04T15:11:47.018Z',\n    updatedAt: '2023-04-04T17:19:50.990Z',\n    environment: { sys: [Object] },\n    firstPublishedAt: '2023-04-04T17:19:25.915Z',\n    createdBy: { sys: [Object] },\n    updatedBy: { sys: [Object] },\n    publishedCounter: 2,\n    version: 9,\n    automationTags: [],\n    contentType: { sys: [Object] }\n  },\n  fields: { key: { 'en-US': 'test.entry' }, value: { 'en-US': 'Test' } }\n}\n```\n\u003c/details\u003e\n\u003chr /\u003e\n\n### • `extractStatusFromSys`\n\nThe function extracts the status of a Contentful Entry from its `sys` properties.\n\n#### Parameters\n- `entrySys` -  The sys properties of the Entry.\n\n#### Return Value\n\nIt returns the status of an Entry: `published`, `changed`, `draft` and `archived` (in the unlikely possibility of an error, it would return `unknown`).\n\n#### Example Usage\n\n```javascript\nconst entry = await getEntry(\n    environment,\n    'exampleEntryId'\n)\n\nconst entryStatus = await extractStatusFromSys(entry?.sys)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(entryStatus)\u003c/code\u003e\u003c/summary\u003e\n\n```\npublished\n```\n\u003c/details\u003e\n\u003chr /\u003e\n\n### • `publishEntry`\n\nPublishes a Contentful entry.\n\n#### Parameters\n- `environment` - Environment Object (you can retrieve it with [getEnvironment](#-getenvironment)).\n- `entryId` - The ID of the entry to publish.\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\n\nA Promise that resolves with `true` if the entry was published successfully, or `false` otherwise.\n\n#### Example Usage\n\n```javascript\nconst isEntryPublished = await publishEntry(\n    environment,\n    'exampleEntryId',\n    2\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(isEntryPublished)\u003c/code\u003e\u003c/summary\u003e\n\n```\ntrue\n```\n\u003c/details\u003e\n\u003chr /\u003e\n\n### • `unpublishEntry`\n\nUnpublishes a Contentful Entry.\n\n#### Parameters\n- `environment` - Environment Object (you can retrieve it with [getEnvironment](#-getenvironment)).\n- `entryId` - The ID of the entry to unpublish.\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\n\nPromise that resolves with `true` if the entry was unpublished successfully, or `false` otherwise.\n\n#### Example Usage\n\n```javascript\nconst isEntryUnpublished = await unpublishEntry(\n    environment,\n    'exampleEntryId',\n    2\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(isEntryUnpublished)\u003c/code\u003e\u003c/summary\u003e\n\n```\ntrue\n```\n\u003c/details\u003e\n\u003chr /\u003e\n\n### • `getTagExists`\n\nThe function checks if a tag exists in a Contentful environment.\n\n#### Parameters\n- `environment` - Environment Object (you can retrieve it with [getEnvironment](#-getenvironment)).\n- `tagId` - The ID of the tag to check.\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\n\nA Promise that resolves with `true` if the tag exists, or `false` otherwise.\n\n#### Example Usage\n\n```javascript\nconst tagExists = await getTagExists(\n    environment,\n    'country-en',\n    2\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(tagExists)\u003c/code\u003e\u003c/summary\u003e\n\n```\ntrue\n```\n\u003c/details\u003e\n\u003chr /\u003e\n\n### • `addEntryTag`\n\nAdds a tag to a Contentful Entry.\n\n#### Parameters\n- `environment` - Environment Object (you can retrieve it with [getEnvironment](#-getenvironment)).\n- `entryId` - he ID of the entry to add the tag to.\n- `tagId` - The ID of the tag to add.\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\n\nA Promise that resolves with `true` if the tag was added successfully, or `false` otherwise.\n\nNote: the entry will need to be republished, after the tag is added. See [publishEntry](#-publishentry).\n\n#### Example Usage\n\n```javascript\nconst isTagAdded = await addEntryTag(\n    environment,\n    'exampleEntryId',\n    'exampleTagId',\n    2\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(isTagAdded)\u003c/code\u003e\u003c/summary\u003e\n\n```\ntrue\n```\n\u003c/details\u003e\n\u003chr /\u003e\n\n### • `removeEntryTag`\n\nRemoves a tag to a Contentful Entry.\n\n#### Parameters\n- `environment` - Environment Object (you can retrieve it with [getEnvironment](#-getenvironment)).\n- `entryId` - he ID of the entry to remove the tag from.\n- `tagId` - The ID of the tag to remove.\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\n\nA Promise that resolves with `true` if the tag was removed successfully, or `false` otherwise.\n\nNote: the entry will need to be republished, after the tag is removed. See [publishEntry](#-publishentry).\n\n#### Example Usage\n\n```javascript\nconst isTagRemoved = await addEntryTag(\n    environment,\n    'exampleEntryId',\n    'exampleTagId',\n    2\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(isTagRemoved)\u003c/code\u003e\u003c/summary\u003e\n\n```\ntrue\n```\n\u003c/details\u003e\n\u003chr /\u003e\n\n### • `deleteEnvironment`\n\nThe function deletes the given Contentful environment, unless it is protected.\n\n#### Parameters\n- `environment` - Environment Object (you can retrieve it with [getEnvironment](#-getenvironment)).\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n- `forbiddenEnvironments` - An array of environment IDs that are protected and cannot be deleted. Default protected environments: `master`, `staging`, `uat`, `dev`.\n\nNote: the function has the `verbosityLevel` as second parameter, instead of the last one. This is to allow using the default value for `forbiddenEnvironments`, hence protecting the production and testing environments.\n\n#### Return Value\nThe function returns true if the environment was successfully deleted, false otherwise.\n\n#### Example Usage\n\n```javascript\nimport { getEnvironment, deleteEnvironment } from 'contentful-lib-helpers'\nimport contentfulManagement from 'contentful-management'\nconst contentfulToken = 'your-access-token'\nconst contentfulSpaceId = 'your-space-id'\nconst contentfulEnvironmentId = 'environment-to-delete'\n\nconst environment = await getEnvironment(\n    contentfulManagement,\n    contentfulToken,\n    contentfulSpaceId,\n    contentfulEnvironmentId,\n    2\n)\n\nconst isEnvironmentDeleted = await deleteEnvironment(\n    environment,\n    2,\n    ['master', 'staging', 'dev']\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(isEnvironmentDeleted)\u003c/code\u003e\u003c/summary\u003e\n\n```\ntrue\n```\n\u003c/details\u003e\n\u003chr /\u003e\n\n### • `getAllLocales`\n\nGet all locales for a given environment.\n\n#### Parameters\n- `environment` - Environment Object (you can retrieve it with [getEnvironment](#-getenvironment)).\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\n\nA Collection of Locale objects.\n\n#### Example Usage\n\n```javascript\nconst allLocales = await getAllLocales(\n    environment,\n    2\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(allLocales)\u003c/code\u003e\u003c/summary\u003e\n\n```js\n{\n  sys: { type: 'Array' },\n  total: 2,\n  skip: 0,\n  limit: 100,\n  items: [\n    {\n      name: 'English (United States)',\n      code: 'en-US',\n      fallbackCode: null,\n      default: true,\n      contentManagementApi: true,\n      contentDeliveryApi: true,\n      optional: false,\n      sys: [Object]\n    },\n    {\n      name: 'Italian (Italy)',\n      code: 'it-IT',\n      fallbackCode: 'en-US',\n      default: false,\n      contentManagementApi: true,\n      contentDeliveryApi: true,\n      optional: true,\n      sys: [Object]\n    }\n  ]\n}\n```\n\u003c/details\u003e\n\u003chr /\u003e\n\n### • `getAllLocalesCode`\n\nGet all the locale codes, as an array of strings (ie: `['en-US', 'it-IT']`)\n\n\n#### Parameters\n- `environment` - Environment Object (you can retrieve it with [getEnvironment](#-getenvironment)).\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\n\nAn array of locale codes.\n\n#### Example Usage\n\n```javascript\nconst allLocalesCode = await getAllLocalesCode(\n    environment,\n    2\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(allLocalesCode)\u003c/code\u003e\u003c/summary\u003e\n\n```js\n[ 'en-US', 'it-IT' ]\n```\n\u003c/details\u003e\n\u003chr /\u003e\n\n### • `getDefaultLocale`\n\nThe function returns the default Locale object.\n\n#### Parameters\n- `environment` - Environment Object (you can retrieve it with [getEnvironment](#-getenvironment)).\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\nThe function returns the locale object of the default locale of the Contentful environment.\n\n#### Example Usage\n\n```javascript\nconst defaultLocale = await getDefaultLocale(\n    environment,\n    2\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(defaultLocale)\u003c/code\u003e\u003c/summary\u003e\n\n```js\n{\n    name: 'English (United States)',\n    code: 'en-US',\n    fallbackCode: null,\n    default: true,\n    contentManagementApi: true,\n    contentDeliveryApi: true,\n    optional: false,\n    sys: {\n        type: 'Locale',\n        id: '3XPgmbnnEyfxxtHVQlcfki',\n        version: 1,\n        space: { sys: [Object] },\n        environment: { sys: [Object] },\n        createdBy: { sys: [Object] },\n        createdAt: '2023-04-04T15:13:55Z',\n        updatedBy: { sys: [Object] },\n        updatedAt: '2023-04-04T15:13:55Z'\n    }\n}\n```\n\u003c/details\u003e\n\u003chr /\u003e\n\n### • `getDefaultLocaleCode`\n\nThe function returns the default Locale code (ie: `en-US`).\n\n#### Parameters\n- `environment` - Environment Object (you can retrieve it with [getEnvironment](#-getenvironment)).\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\nThe function returns default locale code, as a string.\n\n#### Example Usage\n\n```javascript\nconst defaultLocaleCode = await getDefaultLocaleCode(\n    environment,\n    2\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(defaultLocaleCode)\u003c/code\u003e\u003c/summary\u003e\n\n```js\nen-US\n```\n\u003c/details\u003e\n\u003chr /\u003e\n\n### • `getDefaultValuseForLocales`\n\nThis is a very particular function. Passing a 'default' value, that can be anything (`null`, boolean, string, etc), it returns an object whose keys are the locales, and the values are the default value passed.\n\nThis is used by our other NPM package [Contentful CLI Migrations](https://www.npmjs.com/package/contentful-cli-migrations), to build locale-agnostic migrations. Meaning that the locales don't need to be hard-coded when setting up default values in a Contentful Javascript migration.\n\n#### Parameters\n- `environment` - Environment Object (you can retrieve it with [getEnvironment](#-getenvironment)).\n- `defaultValue` - It can be a value of any type (usually `null`, empty string `''` or a boolean value `true/false`)\n\n#### Return Value\nThe function returns an object whose keys are the locales and the values are the default value passed.\n\n#### Example Usage\n\n```javascript\nconst objectDefaultValues = await getDefaultValuesForLocales(\n    environment,\n    true\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(objectDefaultValues)\u003c/code\u003e\u003c/summary\u003e\n\n```js\n{ 'en-US': true, 'it-IT': true }\n```\n\u003c/details\u003e\n\u003chr /\u003e\n\n### • `duplicateEnvironment`\n\nGiven a source Environment id (ie: `master`), it creates a duplicated with a new Environment id. The duplication does not 'copy' the Scheduled Content, for which you will need to use the method [syncScheduledActions](#-syncscheduledactions).\n\n#### Parameters\n- `space` - Differently from other methods, it uses the Space Object (you can retrieve it with [getSpace](#-getspace)).\n- `sourceEnvironmentId` - The source environment that will be duplicated (default: `master`).\n- `destinationEnvironmentId` - The ID/Name of the new environment.\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\nThe function returns an Environment object that can be queried or manipulated to perform further actions.\n\n#### Example Usage\n\n```javascript\nconst newEnvironment = await duplicateEnvironment(\n    space,\n    'master',\n    'release-1.25.5',\n    3\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(newEnvironment)\u003c/code\u003e\u003c/summary\u003e\n\n```js\n{\n  name: 'release-1.25.5',\n  sys: {\n    type: 'Environment',\n    id: 'release-1.25.5',\n    version: 1,\n    space: { sys: [Object] },\n    status: { sys: [Object] },\n    createdBy: { sys: [Object] },\n    createdAt: '2023-07-24T14:19:26Z',\n    updatedBy: { sys: [Object] },\n    updatedAt: '2023-07-24T14:19:26Z',\n    aliases: []\n  }\n}\n```\n\u003c/details\u003e\n\u003chr /\u003e\n\n\n### • `enableCdaKey`\n\nThis function is needed when we want to enable an Environment for a particular CDA Key. For example a duplicate of the `master` Environment will need the same CDA Key that is used to query the current master.\n\n\u003e Note: It's a good habit to name the CDA Key with the same name as the Environment. This because the API can query the Key only by name. So it is recommended to a be a lowercase name without punctuation or spaces.\n\n#### Parameters\n- `space` - Differently from other methods, it uses the Space Object (you can retrieve it with [getSpace](#-getspace)).\n- `cdaKeyName` - The 'name' of the CDA Key. Usually should match an environment name. Recommended to use lowercase, no punctuation and no spaces.\n- `targetEnvironmentId` - The Environment id for which the CDA Key will be enabled.\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\n`true` if the CDA Key has been enabled. `false` otherwise.\n\n#### Example Usage\n\n```javascript\nconst enabledCdaKey = await enableCdaKey(\n    space,\n    'master',\n    'release-1.25.5',\n    3\n)\n```\n\n\u003cdetails\u003e\n    \u003csummary\u003e\u003ccode\u003econsole.log(enabledCdaKey)\u003c/code\u003e\u003c/summary\u003e\n\n```js\ntrue\n```\n\u003c/details\u003e\n\u003chr /\u003e\n\n### • `linkAliasToEnvironment`\n\nGiven an Environment id and and Alias, it links the Alias to that Environment. This function has to be used to switch, for example the current `master` alias to a new release Envirionment.\n\n#### Parameters\n- `space` - Differently from other methods, it uses the Space Object (you can retrieve it with [getSpace](#-getspace)).\n- `sourceEnvironmentId` - The ID of the source Environment that will be linked.\n- `destinationEnvironmentId` - The ID of the Alias to which the Environment will be linked to.\n- `releaseRegEx` - Regular expression to identify release Environments.\n- `protectedEnvironments` - Safety measure when deleting old release to not deleted important Environments.\n- `deleteOldReleases` - If true, it deletes all release Environments, except the newly linked one and the previous one.\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\nThe function does not return any value, but it does return a detailed error message in case of failure.\n\n#### Example Usage\n\n```javascript\nawait linkAliasToEnvironment(\n    space,\n    'release-1.25.5',\n    'master'\n)\n```\n\n### • `syncScheduledActions`\n\nWhen duplicating an Environment, the Scheduled Actions are not usually carried over. This function copies those Scheduled Actions between two environments.\n\n#### Parameters\n- `space` - Differently from other methods, it uses the Space Object (you can retrieve it with [getSpace](#-getspace)).\n- `sourceEnvironmentId` - The source environment that contains the Scheduled Actions.\n- `destinationEnvironmentId` - The destination environment to which those Actions will be copied to.\n- `verbosityLevel` - (optional, default `1`) the level of console logging verbosity to use. See [verbosityLevel](#-verbositylevel).\n\n#### Return Value\nThe function does not return any value, but it does return a detailed error message in case of failure.\n\n#### Example Usage\n\n```javascript\n await syncScheduledActions(\n    space,\n    'master',\n    'release-1.25.5',\n    3\n)\n```\n\n## 🔊 verbosityLevel\nAll methods accept an optional verbosityLevel parameter. This parameter is an integer from 0 to 3 that determines the amount of console logging the function should output. A higher number means more logging. The default value is 1 (error logging)\n\n* `0` - No logging.\n* `1` - Only errors.\n* `2` - Errors and debug information.\n* `3` - All logs, including info logs.\n\n## 📅 Todo\n\n* Add further methods (ie: `getAllAssets`, `uploadAsset`, ...)\n* Improve Logging (+ Colors).\n* Add Tests\n* Add Support for [Yargs](https://www.npmjs.com/package/yargs) and [Chalk](https://www.npmjs.com/package/chalk)\n\n## 👾 Contributors\n\n\u003ctable\u003e\n  \u003ctr\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://github.com/fciacchi\"\u003e\u003cimg src=\"https://images.weserv.nl/?url=avatars.githubusercontent.com/u/58506?v=4\u0026h=100\u0026w=100\u0026fit=cover\u0026mask=circle\u0026maxage=7d\" width=\"100px;\" alt=\"Fabrizio Ciacchi\" /\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003e@fciacchi\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://github.com/psyvic\"\u003e\u003cimg src=\"https://images.weserv.nl/?url=avatars.githubusercontent.com/u/29251597?v=4\u0026h=100\u0026w=100\u0026fit=cover\u0026mask=circle\u0026maxage=7d\" width=\"100px;\" alt=\"Victor Hugo Aizpuruo\" /\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003e@psyvic\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://github.com/aalduz\"\u003e\u003cimg src=\"https://images.weserv.nl/?url=avatars.githubusercontent.com/u/11409770?v=4\u0026h=100\u0026w=100\u0026fit=cover\u0026mask=circle\u0026maxage=7d\" width=\"100px;\" alt=\"Aldo Fernández\" /\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003e@aalduz\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://github.com/leslyto\"\u003e\u003cimg src=\"https://images.weserv.nl/?url=avatars.githubusercontent.com/u/4264812?v=4\u0026h=100\u0026w=100\u0026fit=cover\u0026mask=circle\u0026maxage=7d\" width=\"100px;\" alt=\"Stefan Stoev\" /\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003e@leslyto\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003c/td\u003e\n  \u003c/tr\u003e\n\u003c/table\u003e\n\n### Contributions\nFeel free to open issues or pull requests in our GitHub Repository if you have suggestions or improvements to propose.\n\n## 🎩 Acknowledgements\n\nI would like to express my gratitude to the following parties:\n\n- [Atida 🔗](https://www.atida.com/), the company that has allowed these scripts to be open sourced. Atida is an e-commerce platform that sells beauty and medical products. Their support for open source is greatly appreciated. A special thank to \u003ca href=\"https://github.com/shoopi\"\u003e\u003cimg src=\"https://images.weserv.nl/?url=avatars.githubusercontent.com/u/1385372?v=4\u0026h=16\u0026w=16\u0026fit=cover\u0026mask=circle\u0026maxage=7d\" width=\"16px;\" alt=\"Shaya Pourmirza\" /\u003e Shaya Pourmirza\u003c/a\u003e that has been a great promoter and supporter of this initiative inside the company. \n- [Contentful 🔗](https://www.contentful.com/), for creating their excellent content management platform and the JavaScript CMA SDK that this library is built on. Without their work, this project would not be possible.\n\nThank you to everyone involved!\n\n## 📚 Other Scripts in the same collection\n\nWe produce a bunch of interesting packages for Contentful. You might want to check them out:\n\n* **Contentful Lib Helpers** ([GitHub](https://github.com/AtidaTech/contentful-lib-helpers/) and [NpmJS](https://www.npmjs.com/package/contentful-lib-helpers)): Utility Library for Contentful Management API.\n* **Contentful CLI Export** ([GitHub](https://github.com/AtidaTech/contentful-cli-export/) and [NpmJS](https://www.npmjs.com/package/contentful-cli-export)): Simplifies backup of your Contentful Environment.\n* **Contentful CLI Migrations** ([GitHub](https://github.com/AtidaTech/contentful-cli-migrations/) and [NpmJS](https://www.npmjs.com/package/contentful-cli-migrations)): Tool to automate and scale Contentful Migrations.\n* **Contentful CLI Release** ([GitHub](https://github.com/AtidaTech/contentful-cli-release/) and [NpmJS](https://www.npmjs.com/package/contentful-cli-release)): Release utilities to deploy Contentful in a CI/CD.\n\n[//]: # (* **Contentful CLI Sync** \u0026#40;[GitHub]\u0026#40;https://github.com/AtidaTech/contentful-cli-sync/\u0026#41; and [NpmJS]\u0026#40;https://www.npmjs.com/package/contentful-cli-sync\u0026#41;\u0026#41;: Contentful tool to sync data across Spaces and Environments.)\n\n## 📄 License\nThis project is licensed under the [MIT License](LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fatidatech%2Fcontentful-lib-helpers","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fatidatech%2Fcontentful-lib-helpers","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fatidatech%2Fcontentful-lib-helpers/lists"}