Skip to content

Commit

Permalink
Some more comments, improvements and refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
fciacchi committed Mar 31, 2023
1 parent 857f6af commit eb0dad4
Show file tree
Hide file tree
Showing 22 changed files with 167 additions and 86 deletions.
130 changes: 98 additions & 32 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,33 +1,62 @@
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Build Status](https://travis-ci.com/AtidaTech/contentful-lib-helpers.svg?branch=main)](https://travis-ci.com/AtidaTech/contentful-lib-helpers)
[![npm version](https://badge.fury.io/js/contentful-lib-helpers.svg)](https://npmjs.com/package/contentful-lib-helpers)
![Forks](https://img.shields.io/github/forks/AtidaTech/contentful-lib-helpers)

[comment]: <> ([![Build Status]&#40;https://travis-ci.com/AtidaTech/contentful-lib-helpers.svg?branch=main&#41;]&#40;https://travis-ci.com/AtidaTech/contentful-lib-helpers&#41;)
[comment]: <> (![Version]&#40;https://img.shields.io/github/package-json/v/AtidaTech/contentful-lib-helpers&#41;)
[comment]: <> (![Downloads]&#40;https://img.shields.io/npm/dw/contentful-lib-helpers&#41;)
[comment]: <> (![Forks]&#40;https://img.shields.io/github/forks/AtidaTech/contentful-lib-helpers&#41;)

# Contentful Management API Helper Library

<div style="text-align: center">

# ![Contentful Lib Helpers](./images/logo-helpers-100.png)

</div>

# Contentful CMA Helper Library

A utility library for the Contentful Management API, 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.

## Features
- Easy-to-use functions for common tasks
- Compatible return types with CMA
- Customizable verbosity level for console logging
- Robust error handling and validation
- Promises-based API for easy integration into async workflows

## Installation

To use this helper library, you must have [Node.js](https://nodejs.org/) installed. To install it, simply run:
To use this helper library, you must have [Node.js](https://nodejs.org/) and [npm](http://npmjs.org) installed.

```shee
To install it, simply run:

```shell
npm install contentful-lib-helpers --save
```

Or, if using [yarn](https://yarnpkg.com/lang/en/):

```shell
yarn add contentful-lib-helpers
```

## Usage
Here are the methods available in this toolkit and how to use them:
Here are the methods available in this library and how to use them:
* [getSpace](#getspace)
* [getEnvironment](#getenvironment)

<hr />

### `getSpace(contentfulManagement, contentfulToken, contentfulSpaceId, verbosityLevel = 1)`
### getSpace

```javascript
getSpace(
contentfulManagement,
contentfulToken,
contentfulSpaceId,
verbosityLevel = 1
)
```

The getSpace function retrieves a Contentful space object by ID, using the Contentful Management API.

Expand Down Expand Up @@ -58,7 +87,54 @@ const space = await getSpace(
console.log(space) // { sys: { id: 'your-space-id', ... }, ... }
```

## `verbosityLevel`
<hr />

### getEnvironment
```javascript
getEnvironment(
contentfulManagement,
contentfulToken,
contentfulSpaceId,
contentfulEnvironmentId = 'master',
verbosityLevel = 1
)
```

The getEnvironment function retrieves a Contentful environment object by ID, using the Contentful Management API.

#### Parameters
- `contentfulManagement` - The Contentful Management library.
- `contentfulToken` - The Contentful access token.
- `contentfulSpaceId` - The ID of the space to retrieve.
- `contentfulEnvironmentId` - The ID of the environment to retrieve (default `master`).
- `verbosityLevel` - (optional) the level of console logging verbosity to use. See [Verbosity](#verbositylevel)

#### Return Value
The function returns a Promise that resolves with the Environment object, or null if not found.

#### Example Usage

```javascript
import { getEnvironment } from 'contentful-lib-helpers'
const contentfulManagement = require('contentful-management')
const contentfulToken = 'your-access-token'
const contentfulSpaceId = 'your-space-id'
const contentfulEnvironmentId = 'your-environment-id'

const environment = await getEnvironment(
contentfulManagement,
contentfulToken,
contentfulSpaceId,
contentfulEnvironmentId,
2
)

console.log(environment) // { sys: { id: 'your-environment-id', ... }, ... }
```

<hr />

## verbosityLevel
All 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)

* `0` - No logging.
Expand All @@ -76,9 +152,9 @@ Here a simple example of writing a function that finds an entry by slug, update
**Contentful Management SDK**

```javascript
const contentfulManagement = require('contentful-management')
const contentfulManagement = require('contentful-management')

async function main() {
async function main() {
const client = contentfulManagement.createClient({
accessToken: 'your-access-token',
})
Expand Down Expand Up @@ -133,7 +209,7 @@ Here a simple example of writing a function that finds an entry by slug, update
}
}

main()
await main()
```

</div><div style="float: left; width: 50%;">
Expand All @@ -142,25 +218,19 @@ main()

```javascript
const contentfulManagement = require('contentful-management')
const {
getDefaultLocale,
getEnvironment,
getEntryIdByUniqueField,
addEntryTag,
publishEntry
} = require('@atida/contentful-lib-helpers')
import * as lib from '@atida/contentful-lib-helpers'

async function main() {
const verbosity = 2

const environment = await getEnvironment(
const environment = await lib.getEnvironment(
contentfulManagement,
'your-access-token',
'your-space-id',
'master'
)

const entryId = await getEntryIdByUniqueField(
const entryId = await lib.getEntryIdByUniqueField(
environment,
'page',
'slug',
Expand All @@ -169,27 +239,22 @@ async function main() {
)

if (entryId) {
const locale = await getDefaultLocale (environment, verbosity)
entry.fields.title = {[locale]: 'Updated Title'}
await entry.update()
await addEntryTag(environment, entryId, 'your-tag', verbosity)
await publishEntry(environment, entryId, verbosity)
const entryObject = { title: 'Updated Title' }
await lib.createOrUpdateEntry(environment, entryId, entryObject, null, verbosity)
await lib.addEntryTag(environment, entryId, 'your-tag', verbosity)
await lib.publishEntry(environment, entryId, verbosity)
}
}

main()
await main()
```

</div></div><br clear="all" />


## Todo

* Add further methods:
* `getAssets`
* `uploadAsset`
* `createOrUpdateEntry`
* `duplicateEnvironment` (with `syncScheduledActions`)
* Add further methods (ie: `getAssets`, `uploadAsset`, `duplicateEnvironment`)
* Add Tests
* Publish NPM package

Expand All @@ -200,6 +265,7 @@ main()
<td align="center"><a href="https://github.com/fciacchi"><img src="https://avatars.githubusercontent.com/u/58506?v=4" width="100px;" alt="Fabrizio Ciacchi" style="border-radius: 50%;" /><br /><sub><b>@fciacchi</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/psyvic"><img src="https://avatars.githubusercontent.com/u/29251597?v=4" width="100px;" alt="Victor Hugo Aizpuruo" style="border-radius: 50%;" /><br /><sub><b>@psyvic</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/aalduz"><img src="https://avatars.githubusercontent.com/u/11409770?v=4" width="100px;" alt="Aldo Fernández" style="border-radius: 50%;" /><br /><sub><b>@aalduz</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/leslyto"><img src="https://avatars.githubusercontent.com/u/4264812?v=4" width="100px;" alt="Stefan Stoev" style="border-radius: 50%;" /><br /><sub><b>@leslyto</b></sub></a><br /></td>
</tr>
</table>

Expand All @@ -208,7 +274,7 @@ main()

I would like to express my gratitude to the following parties:

- [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.
- [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 <a href="https://github.com/shoopi"><img src="https://avatars.githubusercontent.com/u/1385372?v=4" width="16px;" alt="Shaya Pourmirza" style="border-radius: 50%;" /> Shaya Pourmirza</a> that has been a great promoter and supporter of this initiative inside the company.
- [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.

Thank you to everyone involved!
Expand Down
Binary file added images/logo-helpers-100.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/logo-helpers.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
15 changes: 15 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export * from './lib/addEntryTag'
export * from './lib/deleteEnvironment'
export * from './lib/extractStatusFromSys'
export * from './lib/getAllEntriesByContentType'
export * from './lib/getAllLocales'
export * from './lib/getContentType'
export * from './lib/getContentTypes'
export * from './lib/getDefaultLocale'
export * from './lib/getEntry'
export * from './lib/getEntryIdByUniqueField'
export * from './lib/getEnvironment'
export * from './lib/getSpace'
export * from './lib/getTagExists'
export * from './lib/publishEntry'
export * from './lib/removeEntryTag'
8 changes: 5 additions & 3 deletions lib/addEntryTag.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { getTagExists } from './getTagExists'
import { getEntry } from './getEntry'
import { validateInputs } from './validation/validateInputs'
import { validateString } from './validation/validateString'

Expand All @@ -8,13 +9,14 @@ import { validateString } from './validation/validateString'
* @param {import("contentful-management/dist/typings/entities/environment").Environment} environment - The Contentful environment object.
* @param {string} entryId - The ID of the entry to add the tag to.
* @param {string} tagId - The ID of the tag to add.
* @param {number} [verbosityLevel=1] - The verbosity level of the logging (0 = NONE, 1 = ERROR, 2 = DEBUG, 3 = INFO).
* @param {number} [verbosityLevel=1] - 0 = NONE, 1 = ERROR, 2 = DEBUG, 3 = INFO
* @returns {Promise<boolean>} - A Promise that resolves with `true` if the tag was added successfully, or `false` otherwise.
*
* @example
*
* Usage:
* const environment = await client.getEnvironment(environmentId)
* const cmaClass = require('contentful-management')
* const environment = await getEnvironment(cmaClass, 'access-token', 'space-id', 'environment-id')
* const entryId = 'exampleEntryId'
* const tagId = 'exampleTagId'
* const added = await addEntryTag(environment, entryId, tagId, 2)
Expand Down Expand Up @@ -51,7 +53,7 @@ export async function addEntryTag(
}

try {
const entry = await environment.getEntry(entryId)
const entry = await getEntry(environment, entryId, verbosityLevel)

if (!entry || typeof entry.update !== 'function') {
console.error(
Expand Down
7 changes: 4 additions & 3 deletions lib/deleteEnvironment.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@
*
* @param {import("contentful-management/dist/typings/entities/environment").Environment} environment - The environment to delete.
* @param {string[]} forbiddenEnvironments - An array of environment IDs that are protected and cannot be deleted.
* @param {number} [verbosityLevel=1] - The level of verbosity of the console logs. A higher number means more logs.
* @param {number} [verbosityLevel=1] - 0 = NONE, 1 = ERROR, 2 = DEBUG, 3 = INFO
* @returns {Promise<boolean>} - True if the environment was successfully deleted, false otherwise.
*
* @example
*
* Usage:
* const cmaClass = require('contentful-management')
* const environment = await getEnvironment(cmaClass, 'access-token', 'space-id', 'environment-id')
*
* // Deleting an environment with the default configuration
* const environment = await contentful.getEnvironment(environmentId)
* const result = await deleteEnvironment(environment)
* // Deleting an environment with custom configuration
* const environment = await contentful.getEnvironment(environmentId)
* const result = await deleteEnvironment(environment, ['test', 'prod'], 2)
*/
export async function deleteEnvironment(
Expand Down
3 changes: 2 additions & 1 deletion lib/extractStatusFromSys.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ const EntityStatus = {
* @example
*
* Usage:
* const environment = await contentful.getEnvironment(environmentId)
* const cmaClass = require('contentful-management')
* const environment = await getEnvironment(cmaClass, 'access-token', 'space-id', 'environment-id')
* const entry = await getEntry(environment, entryId)
* const status = await extractStatusFromSys(entry.sys) // 'changed'
*/
Expand Down
2 changes: 1 addition & 1 deletion lib/getAllEntriesByContentType.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { validateString } from './validation/validateString'
* @param {import("contentful-management/dist/typings/entities/environment").Environment} environment - The Contentful environment object.
* @param {string} contentTypeId - The ID of the content-type to retrieve.
* @param {number} [limit=1000] - Number of entries to retrieve at each loops.
* @param {number} [verbosityLevel=1] - The verbosity level of the logging (0 = NONE, 1 = ERROR, 2 = DEBUG, 3 = INFO).
* @param {number} [verbosityLevel=1] - 0 = NONE, 1 = ERROR, 2 = DEBUG, 3 = INFO
* @returns {Promise<Array<import("contentful-management/dist/typings/entities/entry").Entry>>}
*/
export async function getAllEntriesByContentType(
Expand Down
5 changes: 3 additions & 2 deletions lib/getAllLocales.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ import { validateInputs } from './validation/validateInputs'
* Get all locales for a given environment
*
* @param {import("contentful-management/dist/typings/entities/environment").Environment} environment - The Contentful Environment object
* @param {number} [verbosityLevel=1] - The verbosity level of the logging (0 = NONE, 1 = ERROR, 2 = DEBUG, 3 = INFO)
* @param {number} [verbosityLevel=1] - 0 = NONE, 1 = ERROR, 2 = DEBUG, 3 = INFO
* @returns {Promise<import("contentful-management").Collection<import("contentful-management").Locale>>} - An array of Locale objects
*
* @example
*
* // Usage:
* const environment = await client.getEnvironment(environmentId);
* const cmaClass = require('contentful-management')
* const environment = await getEnvironment(cmaClass, 'access-token', 'space-id', 'environment-id')
* const locales = await getAllLocales(environment, 2);
* console.log(locales.items);
*/
Expand Down
5 changes: 3 additions & 2 deletions lib/getContentType.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@ import { validateString } from './validation/validateString'
*
* @param {import("contentful-management/dist/typings/entities/environment").Environment} environment - The Contentful environment object.
* @param {string} contentTypeId - The ID of the content-type to retrieve.
* @param {number} [verbosityLevel=1] - The verbosity level of the logging (0 = NONE, 1 = ERROR, 2 = DEBUG, 3 = INFO).
* @param {number} [verbosityLevel=1] - 0 = NONE, 1 = ERROR, 2 = DEBUG, 3 = INFO
* @returns {Promise<import("contentful-management/dist/typings/entities/content-type").ContentType|null>} - A Promise that resolves with the content-type object if it exists, or `null` otherwise.
*
* @example
*
* Usage:
* const environment = await client.getEnvironment(environmentId)
* const cmaClass = require('contentful-management')
* const environment = await getEnvironment(cmaClass, 'access-token', 'space-id', 'environment-id')
* const contentTypeId = 'exampleContentTypeId'
* const contentType = await getContentType(environment, contentTypeId, 2)
* console.log(contentType) // {sys: {...}, ...}
Expand Down
5 changes: 3 additions & 2 deletions lib/getContentTypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ import { validateInputs } from './validation/validateInputs'
* Get all Content-types in a Contentful environment.
*
* @param {import("contentful-management/dist/typings/entities/environment").Environment} environment - The Contentful Environment object.
* @param {number} [verbosityLevel=1] - The verbosity level of the logging (0 = NONE, 1 = ERROR, 2 = DEBUG, 3 = INFO).
* @param {number} [verbosityLevel=1] - 0 = NONE, 1 = ERROR, 2 = DEBUG, 3 = INFO
* @returns {Promise<import("contentful-management/dist/typings/common-types").Collection<import("contentful-management/dist/typings/entities/content-type").ContentType, import("contentful-management/dist/typings/entities/content-type").ContentTypeProps> | []>} - A Promise that resolves with a Content-type collection if successful, or an empty array otherwise.
*
* @example
*
* Usage:
* const environment = await client.getEnvironment(environmentId)
* const cmaClass = require('contentful-management')
* const environment = await getEnvironment(cmaClass, 'access-token', 'space-id', 'environment-id')
* const contentTypes = await getContentTypes(environment, 2)
* console.log(contentTypes) // ContentTypeCollection { sys: { type: 'Array' }, total: 3, skip: 0, limit: 100, items: [ {...}, {...}, {...} ] }
*/
Expand Down
5 changes: 3 additions & 2 deletions lib/getDefaultLocale.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ import { validateInputs } from './validation/validateInputs'

/**
* @param {import("contentful-management/dist/typings/entities/environment").Environment} environment - The Contentful Environment object
* @param {number} [verbosityLevel=1] - The verbosity level of the logging (0 = NONE, 1 = ERROR, 2 = DEBUG, 3 = INFO)
* @param {number} [verbosityLevel=1] - 0 = NONE, 1 = ERROR, 2 = DEBUG, 3 = INFO
* @returns {Promise<import("contentful-management/dist/typings/entities/locale").Locale,import("contentful-management/dist/typings/entities/locale").LocaleProps|null>} locale - The default Locale object
*
* @example
*
* // Usage
* const environment = await client.getEnvironment(environmentId);
* const cmaClass = require('contentful-management')
* const environment = await getEnvironment(cmaClass, 'access-token', 'space-id', 'environment-id')
* const defaultLocale = await getDefaultLocale(environment, 2);
* console.log(defaultLocale.code) // Outputs the code of the default Locale object.
*/
Expand Down
Loading

0 comments on commit eb0dad4

Please sign in to comment.