Skip to content

Commit

Permalink
chore(SDK: dotcms client): Improve JS Client README.md (#30677)
Browse files Browse the repository at this point in the history
This pull request includes significant updates to the
`core-web/libs/sdk/client/README.md` file to improve the documentation
for the DotCMS API Client. The changes include a more detailed
introduction, additional usage examples, and comprehensive instructions
for using various methods of the client.

Documentation improvements:

* Updated the introduction to provide a clearer description of the
`@dotcms/client` library and its capabilities.
* Added detailed usage examples for fetching pages, navigation, and
collections of content, including complex queries, sorting, filtering by
language, and handling draft content.
* Included an example for error handling to demonstrate how to manage
errors gracefully using a `try-catch` block.
* Expanded the API reference section to include the `getCollection`
method and its parameters, return values, and usage.
  • Loading branch information
rjvelazco authored Nov 15, 2024
1 parent ec2d2ef commit 656775a
Showing 1 changed file with 141 additions and 8 deletions.
149 changes: 141 additions & 8 deletions core-web/libs/sdk/client/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# @dotcms/client
# DotCMS API Client - `@dotcms/client`

`@dotcms/client` is the official dotCMS JavaScript library designed to simplify interactions with the DotCMS REST APIs.
The `@dotcms/client` is a JavaScript/TypeScript library for interacting with a DotCMS instance. It allows you to easily fetch pages, content, and navigation information in JSON format, as well as to make complex queries on content collections.

This client library provides a streamlined, promise-based interface to fetch pages and navigation API.

Expand All @@ -10,9 +10,11 @@ This client library provides a streamlined, promise-based interface to fetch pag
- Support for custom actions to communicate with the DotCMS page editor.
- Comprehensive TypeScript typings for better development experience.

# DotCMS API Client

## Installation

Install the package via npm:
To get started, install the client via npm or yarn:

```bash
npm install @dotcms/client
Expand Down Expand Up @@ -52,30 +54,150 @@ const client = DotCmsClient.init({

### Fetching a Page

Retrieve the elements of any page in your DotCMS system in JSON format.
You can retrieve the elements of any page in your DotCMS system in JSON format using the client.page.get() method.

```javascript
const pageData = await client.page.get({
path: '/your-page-path',
language_id: 1,
personaId: 'optional-persona-id'
});

console.log(pageData);
```

### Fetching Navigation

Retrieve information about the DotCMS file and folder tree.
Retrieve the DotCMS file and folder tree to get information about the navigation structure.

```javascript
const navData = await client.nav.get({
path: '/',
depth: 2,
languageId: 1
});
```

### Fetching a Collection of Content

The `getCollection` method allows you to fetch a collection of content items using a builder pattern for complex queries.

#### Basic Usage

Here’s a simple example to fetch content from a collection:

```typescript
import { DotCmsClient } from '@dotcms/client';

const client = DotCmsClient.init({
dotcmsUrl: 'https://your-dotcms-instance.com',
authToken: 'your-auth-token'
});

const collectionResponse = await client.content
.getCollection('Blog') // Collection name
.limit(10) // Limit results to 10 items
.page(1) // Fetch the first page
.fetch(); // Execute the query

console.log(collectionResponse.contentlets);
```

#### Sorting Content

You can sort the content by any field in ascending or descending order:

```typescript
const sortedResponse = await client.content
.getCollection('Blog')
.sortBy([{ field: 'title', order: 'asc' }]) // Sort by title in ascending order
.fetch();
```

#### Filtering by Language

If you need to filter content by language, you can specify the `language` parameter:

```typescript
const languageFilteredResponse = await client.content
.getCollection('Blog')
.language(2) // Filter by language ID (e.g., 2)
.fetch();
```

#### Using Complex Queries

You can build more complex queries using the query builder. For example, filter by author and `title`:

console.log(navData);
```typescript
const complexQueryResponse = await client.content
.getCollection('Blog')
.query((qb) => qb.field('author').equals('John Doe').and().field('title').equals('Hello World'))
.fetch();
```

#### Fetching Draft Content

To only fetch draft content, use the `draft()` method:

```typescript
const draftContentResponse = await client.content
.getCollection('Blog')
.draft() // Fetch only drafts content
.fetch();
```

#### Setting Depth for Relationships

To fetch content with a specific relationship depth, use the `depth()` method:

```typescript
const depthResponse = await client.content
.getCollection('Blog')
.depth(2) // Fetch related content up to depth 2
.fetch();
```

#### Combining Multiple Methods

You can combine multiple methods to build more complex queries. For example, limit results, sort them, and filter by author:

```typescript
const combinedResponse = await client.content
.getCollection('Blog')
.limit(5)
.page(2)
.sortBy([{ field: 'title', order: 'asc' }])
.query((qb) => qb.field('author').equals('John Doe'))
.depth(1)
.fetch();
```

## Error Handling Example

To handle errors gracefully, you can use a `try-catch` block around your API calls. Here’s an example:

```typescript
try {
const pageData = await client.page.get({
path: '/your-page-path',
languageId: 1
});
} catch (error) {
console.error('Failed to fetch page data:', error);
}
```

This ensures that any errors that occur during the fetch (e.g., network issues, invalid paths, etc.) are caught and logged properly.

## Pagination

When fetching large collections of content, pagination is key to managing the number of results returned:

```typescript
const paginatedResponse = await client.content
.getCollection('Blog')
.limit(10) // Limit to 10 items per page
.page(2) // Get the second page of results
.fetch();
```

## API Reference
Expand All @@ -94,6 +216,17 @@ Retrieves the specified page's elements from your DotCMS system in JSON format.

Retrieves information about the DotCMS file and folder tree.

### `DotCmsClient.content.getCollection(contentType: string): CollectionBuilder<T>`
Creates a builder to filter and fetch a collection of content items for a specific content type.

#### Parameters

contentType (string): The content type to retrieve.

#### Returns

CollectionBuilder<T>: A builder instance for chaining filters and executing the query.

## Contributing

GitHub pull requests are the preferred method to contribute code to dotCMS. Before any pull requests can be accepted, an automated tool will ask you to agree to the [dotCMS Contributor's Agreement](https://gist.github.com/wezell/85ef45298c48494b90d92755b583acb3).
Expand Down

0 comments on commit 656775a

Please sign in to comment.