@ibm-cloud/cloudant 0.12.7 → 0.12.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -1914
- package/auth/couchdbSessionAuthenticator.js +0 -1
- package/auth/couchdbSessionAuthenticator.js.map +1 -1
- package/auth/sessionTokenManager.js +3 -4
- package/auth/sessionTokenManager.js.map +1 -1
- package/cloudant/features/changesFollower.d.ts +0 -22
- package/cloudant/features/changesFollower.js +22 -18
- package/cloudant/features/changesFollower.js.map +1 -1
- package/cloudant/features/changesParamsHelper.d.ts +5 -1
- package/cloudant/features/changesParamsHelper.js +16 -11
- package/cloudant/features/changesParamsHelper.js.map +1 -1
- package/cloudant/features/changesResultIterator.d.ts +3 -1
- package/cloudant/features/changesResultIterator.js +19 -12
- package/cloudant/features/changesResultIterator.js.map +1 -1
- package/cloudant/features/pagination/allDocsBasePageIterator.d.ts +2 -3
- package/cloudant/features/pagination/allDocsBasePageIterator.js +1 -7
- package/cloudant/features/pagination/allDocsBasePageIterator.js.map +1 -1
- package/cloudant/features/pagination/allDocsPageIterator.d.ts +1 -2
- package/cloudant/features/pagination/allDocsPageIterator.js +0 -4
- package/cloudant/features/pagination/allDocsPageIterator.js.map +1 -1
- package/cloudant/features/pagination/allDocsPartitionPageIterator.d.ts +1 -2
- package/cloudant/features/pagination/allDocsPartitionPageIterator.js +0 -4
- package/cloudant/features/pagination/allDocsPartitionPageIterator.js.map +1 -1
- package/cloudant/features/pagination/basePageIterator.d.ts +1 -1
- package/cloudant/features/pagination/basePageIterator.js +7 -9
- package/cloudant/features/pagination/basePageIterator.js.map +1 -1
- package/cloudant/features/pagination/bookmarkPageIterator.d.ts +1 -4
- package/cloudant/features/pagination/bookmarkPageIterator.js +2 -13
- package/cloudant/features/pagination/bookmarkPageIterator.js.map +1 -1
- package/cloudant/features/pagination/designDocsPageIterator.d.ts +1 -2
- package/cloudant/features/pagination/designDocsPageIterator.js +0 -4
- package/cloudant/features/pagination/designDocsPageIterator.js.map +1 -1
- package/cloudant/features/pagination/findBasePageIterator.d.ts +1 -2
- package/cloudant/features/pagination/findBasePageIterator.js +4 -8
- package/cloudant/features/pagination/findBasePageIterator.js.map +1 -1
- package/cloudant/features/pagination/findPageIterator.d.ts +1 -2
- package/cloudant/features/pagination/findPageIterator.js +0 -4
- package/cloudant/features/pagination/findPageIterator.js.map +1 -1
- package/cloudant/features/pagination/findPartitionPageIterator.d.ts +1 -2
- package/cloudant/features/pagination/findPartitionPageIterator.js +0 -4
- package/cloudant/features/pagination/findPartitionPageIterator.js.map +1 -1
- package/cloudant/features/pagination/iteratorPager.js +2 -1
- package/cloudant/features/pagination/iteratorPager.js.map +1 -1
- package/cloudant/features/pagination/keyPageIterator.d.ts +5 -7
- package/cloudant/features/pagination/keyPageIterator.js +12 -18
- package/cloudant/features/pagination/keyPageIterator.js.map +1 -1
- package/cloudant/features/pagination/pagination.js +3 -2
- package/cloudant/features/pagination/pagination.js.map +1 -1
- package/cloudant/features/pagination/searchBasePageIterator.d.ts +0 -1
- package/cloudant/features/pagination/searchBasePageIterator.js +0 -4
- package/cloudant/features/pagination/searchBasePageIterator.js.map +1 -1
- package/cloudant/features/pagination/searchPageIterator.d.ts +1 -2
- package/cloudant/features/pagination/searchPageIterator.js +0 -4
- package/cloudant/features/pagination/searchPageIterator.js.map +1 -1
- package/cloudant/features/pagination/searchPartitionPageIterator.d.ts +1 -2
- package/cloudant/features/pagination/searchPartitionPageIterator.js +0 -4
- package/cloudant/features/pagination/searchPartitionPageIterator.js.map +1 -1
- package/cloudant/features/pagination/viewBasePageIterator.d.ts +2 -3
- package/cloudant/features/pagination/viewBasePageIterator.js +3 -10
- package/cloudant/features/pagination/viewBasePageIterator.js.map +1 -1
- package/cloudant/features/pagination/viewPageIterator.d.ts +1 -2
- package/cloudant/features/pagination/viewPageIterator.js +0 -4
- package/cloudant/features/pagination/viewPageIterator.js.map +1 -1
- package/cloudant/features/pagination/viewPartitionPageIterator.d.ts +1 -2
- package/cloudant/features/pagination/viewPartitionPageIterator.js +0 -4
- package/cloudant/features/pagination/viewPartitionPageIterator.js.map +1 -1
- package/cloudant/v1.d.ts +12 -12
- package/cloudant/v1.js +4 -4
- package/cloudant/v1.js.map +1 -1
- package/index.js.map +1 -1
- package/lib/cloudantBaseService.d.ts +1 -1
- package/lib/cloudantBaseService.js +2 -1
- package/lib/cloudantBaseService.js.map +1 -1
- package/lib/getAuthenticatorFromEnvCloudantExtension.d.ts +1 -1
- package/lib/getAuthenticatorFromEnvCloudantExtension.js +1 -1
- package/lib/getAuthenticatorFromEnvCloudantExtension.js.map +1 -1
- package/package.json +10 -11
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
[](https://github.com/IBM/cloudant-node-sdk/releases/latest)
|
|
3
3
|
[](https://ibm.github.io/cloudant-node-sdk/)
|
|
4
4
|
|
|
5
|
-
# IBM Cloudant Node.js SDK Version 0.12.
|
|
5
|
+
# IBM Cloudant Node.js SDK Version 0.12.9
|
|
6
6
|
|
|
7
7
|
IBM Cloudant Node.js SDK is a client library that interacts with the
|
|
8
8
|
[IBM Cloudant APIs](https://cloud.ibm.com/apidocs/cloudant?code=node).
|
|
@@ -25,61 +25,15 @@ to avoid surprises.
|
|
|
25
25
|
- [Installation](#installation)
|
|
26
26
|
- [Using the SDK](#using-the-sdk)
|
|
27
27
|
* [Authentication](#authentication)
|
|
28
|
-
+ [Authentication with environment variables](#authentication-with-environment-variables)
|
|
29
|
-
- [IAM API key authentication](#iam-api-key-authentication)
|
|
30
|
-
- [IAM Trusted profile (container) authentication](#iam-trusted-profile-container-authentication)
|
|
31
|
-
- [IAM Trusted profile (VPC) authentication](#iam-trusted-profile-vpc-authentication)
|
|
32
|
-
- [IAM Trusted profile (assume identity) authentication](#iam-trusted-profile-assume-identity-authentication)
|
|
33
|
-
- [Session cookie authentication](#session-cookie-authentication)
|
|
34
|
-
+ [Authentication with external configuration](#authentication-with-external-configuration)
|
|
35
|
-
+ [Programmatic authentication](#programmatic-authentication)
|
|
36
28
|
* [Automatic retries](#automatic-retries)
|
|
37
29
|
* [Request timeout configuration](#request-timeout-configuration)
|
|
38
30
|
* [Code examples](#code-examples)
|
|
39
|
-
+ [1. Create a database and add a document](#1-create-a-database-and-add-a-document)
|
|
40
|
-
+ [2. Retrieve information from an existing database](#2-retrieve-information-from-an-existing-database)
|
|
41
|
-
+ [3. Update your previously created document](#3-update-your-previously-created-document)
|
|
42
|
-
+ [4. Delete your previously created document](#4-delete-your-previously-created-document)
|
|
43
|
-
+ [Further code examples](#further-code-examples)
|
|
44
31
|
* [Error handling](#error-handling)
|
|
45
32
|
* [Raw IO](#raw-io)
|
|
46
33
|
* [Further resources](#further-resources)
|
|
47
34
|
* [Browser usage](#browser-usage)
|
|
48
35
|
+ [Polyfills](#polyfills)
|
|
49
36
|
+ [CORS](#cors)
|
|
50
|
-
* [Changes feed follower](#changes-feed-follower)
|
|
51
|
-
+ [Introduction](#introduction)
|
|
52
|
-
+ [Modes of operation](#modes-of-operation)
|
|
53
|
-
+ [Configuring the changes follower](#configuring-the-changes-follower)
|
|
54
|
-
+ [Error suppression](#error-suppression)
|
|
55
|
-
+ [Follower operation](#follower-operation)
|
|
56
|
-
+ [Checkpoints](#checkpoints)
|
|
57
|
-
+ [Code examples](#code-examples-1)
|
|
58
|
-
- [Initializing a changes follower](#initializing-a-changes-follower)
|
|
59
|
-
- [Starting the changes follower](#starting-the-changes-follower)
|
|
60
|
-
* [Start mode for continuous listening](#start-mode-for-continuous-listening)
|
|
61
|
-
* [Start mode for one-off fetching](#start-mode-for-one-off-fetching)
|
|
62
|
-
- [Processing changes](#processing-changes)
|
|
63
|
-
* [Process continuous changes](#process-continuous-changes)
|
|
64
|
-
* [Process one-off changes](#process-one-off-changes)
|
|
65
|
-
- [Stopping the changes follower](#stopping-the-changes-follower)
|
|
66
|
-
* [Pagination (beta)](#pagination-beta)
|
|
67
|
-
+ [Introduction](#introduction-1)
|
|
68
|
-
+ [Limitations](#limitations)
|
|
69
|
-
+ [Capacity considerations](#capacity-considerations)
|
|
70
|
-
+ [Available operations](#available-operations)
|
|
71
|
-
+ [Creating a pagination](#creating-a-pagination)
|
|
72
|
-
- [Initialize the service](#initialize-the-service)
|
|
73
|
-
- [Set the options](#set-the-options)
|
|
74
|
-
- [Create the pagination](#create-the-pagination)
|
|
75
|
-
+ [Using pagination](#using-pagination)
|
|
76
|
-
- [Stream pages](#stream-pages)
|
|
77
|
-
- [Stream rows](#stream-rows)
|
|
78
|
-
- [Iterate pages](#iterate-pages)
|
|
79
|
-
- [Iterate rows](#iterate-rows)
|
|
80
|
-
- [Pager](#pager)
|
|
81
|
-
* [Get each page from a pager](#get-each-page-from-a-pager)
|
|
82
|
-
* [Get all results from a pager](#get-all-results-from-a-pager)
|
|
83
37
|
- [Questions](#questions)
|
|
84
38
|
- [Issues](#issues)
|
|
85
39
|
- [Versioning and LTS support](#versioning-and-lts-support)
|
|
@@ -114,8 +68,8 @@ project:
|
|
|
114
68
|
- Handles the authentication.
|
|
115
69
|
- Familiar user experience with IBM Cloud SDKs.
|
|
116
70
|
- Flexibility to use either built-in models or byte-based requests and responses for documents.
|
|
117
|
-
- Built-in [Changes feed follower](
|
|
118
|
-
- Built-in [Pagination](
|
|
71
|
+
- Built-in [Changes feed follower](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.9/docs/Changes_Follower.md)
|
|
72
|
+
- Built-in [Pagination](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.9/docs/Pagination.md) (beta)
|
|
119
73
|
- `Promise` based design with asynchronous HTTP requests.
|
|
120
74
|
- Use either as native JavaScript or take advantage of TypeScript models.
|
|
121
75
|
- Transparently compresses request and response bodies.
|
|
@@ -140,135 +94,38 @@ npm install @ibm-cloud/cloudant
|
|
|
140
94
|
For fundamental SDK usage information and config options, please see the common [IBM Cloud SDK](https://github.com/IBM/ibm-cloud-sdk-common/blob/main/README.md) documentation.
|
|
141
95
|
|
|
142
96
|
This library requires configuration with a service URL and
|
|
143
|
-
[Cloudant service credentials]
|
|
97
|
+
[Cloudant service credentials][service-credentials] to authenticate with your
|
|
144
98
|
account.
|
|
145
99
|
|
|
146
100
|
There are several ways to **set** these authentication properties:
|
|
147
101
|
|
|
148
|
-
1. As [environment variables](#authentication-with-environment-variables)
|
|
149
|
-
2. The [programmatic approach](#programmatic-authentication)
|
|
150
|
-
3. With an [external credentials file](#authentication-with-external-configuration)
|
|
102
|
+
1. As [environment variables](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.9/docs/Authentication.md#authentication-with-environment-variables)
|
|
103
|
+
2. The [programmatic approach](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.9/docs/Authentication.md#programmatic-authentication)
|
|
104
|
+
3. With an [external credentials file](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.9/docs/Authentication.md#authentication-with-external-configuration)
|
|
151
105
|
|
|
152
106
|
The following section describes the different authentication types and provides environment variable examples.
|
|
153
107
|
Examples for other configuration methods are available by following the provided links.
|
|
154
108
|
|
|
155
109
|
### Authentication
|
|
156
110
|
|
|
111
|
+
Consult the [authentication document](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.9/docs/Authentication.md)
|
|
112
|
+
for comprehensive details of all the available authentication methods and how to configure them with environment settings
|
|
113
|
+
or programmatically.
|
|
157
114
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
* [IBM Cloudant service credentials](https://cloud.ibm.com/docs/Cloudant?topic=Cloudant-locating-your-service-credentials) generated by the IBM Cloud Cloudant resource instance.
|
|
163
|
-
* Username and password credentials (with authentication types `COUCHDB_SESSION` and `BASIC`)
|
|
164
|
-
* [IBM Cloudant service credentials](https://cloud.ibm.com/docs/Cloudant?topic=Cloudant-locating-your-service-credentials) generated for an IBM Cloud Cloudant resource instance not configured as `IAM only`.
|
|
165
|
-
* IBM Cloudant [legacy credentials](https://cloud.ibm.com/docs/Cloudant?topic=Cloudant-work-with-your-account#basic-authentication) (username and password) for instances not in IBM Cloud.
|
|
166
|
-
* IBM Cloudant [legacy API keys](https://cloud.ibm.com/docs/Cloudant?topic=Cloudant-work-with-your-account#api-keys).
|
|
167
|
-
|
|
168
|
-
| Authentication type | Recommended for | `AUTH_TYPE` | Description |
|
|
169
|
-
| --- | --- | --- | --- |
|
|
170
|
-
| IAM Trusted Profiles (compute resource [container](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md#container-authentication)) | Cloudant<BR>(SDK running in IBM Cloud IKS) | `CONTAINER` | Obtains a compute resource (CR) token from the container.<BR>Exchanges the CR token for an IAM `access_token`.<BR>Adds an `Authorization: Bearer <access_token>` header to each HTTP request.<BR>Automatically renews the access token when needed. |
|
|
171
|
-
| IAM Trusted Profiles (compute resource [VPC](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md#vpc-instance-authentication)) | Cloudant<BR>(SDK running in IBM Cloud VPC) | `VPC` | Obtains an identity token from the VPC instance metadata.<BR>Exchanges the identity token for an IAM `access_token`.<BR>Adds an `Authorization: Bearer <access_token>` header to each HTTP request.<BR>Automatically renews the access token when needed. |
|
|
172
|
-
| IAM Trusted Profiles ([assume identity](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md#identity-and-access-management-iam-authentication-grant-type-assume)) | Cloudant | `IAMASSUME` | Exchanges an IAM API key for an IAM `access_token` (same as `IAM` auth type).<BR>Uses that initial token to obtain a second `access_token` from IAM with the assumed identity information.<BR>Adds an `Authorization: Bearer <access_token>` header to each HTTP request.<BR>Automatically renews the access token when needed. |
|
|
173
|
-
| [IAM API key](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md#identity-and-access-management-iam-authentication-grant-type-apikey) | Cloudant | `IAM` | Exchanges an IAM API key for an IAM `access_token`.<BR>Adds an `Authorization: Bearer <access_token>` header to each HTTP request.<BR>Automatically renews the access token when needed. |
|
|
174
|
-
| [Session cookie](#session-cookie-authentication) | [Cloudant](https://cloud.ibm.com/docs/Cloudant?topic=Cloudant-work-with-your-account#cookie-authentication)<BR>(legacy credentials & instances without IAM)<BR><BR>[Apache CouchDB](https://docs.couchdb.org/en/stable/api/server/authn.html#cookie-authentication) | `COUCHDB_SESSION` | Exchanges credentials with `/_session` endpoint to retrieve a cookie.<BR>Adds `Cookie` header and content to each HTTP request.<BR>Automatically renews session when needed. |
|
|
175
|
-
| [Bearer token](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md#bearer-token-authentication) | [Apache CouchDB](https://docs.couchdb.org/en/stable/api/server/authn.html#jwt-authentication)<BR>(using JWT authentication) | `BEARERTOKEN` | Adds an `Authorization: Bearer <token>` to each HTTP request.<BR>No token management or renewal.<BR>Also compatible with IAM access tokens managed independently of the SDK. |
|
|
176
|
-
| [Basic](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md#basic-authentication) | [Apache CouchDB](https://docs.couchdb.org/en/stable/api/server/authn.html#basic-authentication)<BR>(if cookies are not enabled) | `BASIC` | Adds an `Authorization: Basic <encoded username and password>` header to each HTTP request. |
|
|
177
|
-
| [None](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md#no-auth-authentication) | - | `NOAUTH` | Note that this authentication type only works for operations against a database allowing access for unauthenticated users. |
|
|
178
|
-
|
|
179
|
-
The default authentication type for the SDK is `CONTAINER` unless supplying `APIKEY` configuration, which changes the default authentication type to `IAM`.
|
|
180
|
-
|
|
181
|
-
#### Authentication with environment variables
|
|
182
|
-
|
|
183
|
-
The default service name is `CLOUDANT` so these examples use `CLOUDANT_` prefixed names.
|
|
184
|
-
|
|
185
|
-
Any custom service name prefix is valid, provided it matches the name used to instantiate the SDK client
|
|
186
|
-
and applied to all configuration options.
|
|
187
|
-
|
|
188
|
-
##### IAM API key authentication
|
|
189
|
-
|
|
190
|
-
For Cloudant *IAM API key authentication*, set the following environmental variables by
|
|
191
|
-
replacing the `<url>` and `<apikey>` with your proper
|
|
192
|
-
[service credentials](https://cloud.ibm.com/docs/Cloudant?topic=Cloudant-locating-your-service-credentials). There is no need to set
|
|
193
|
-
`CLOUDANT_AUTH_TYPE` to `IAM` because it is the default when supplying an `APIKEY`.
|
|
194
|
-
|
|
195
|
-
```bash
|
|
196
|
-
CLOUDANT_URL=<url>
|
|
197
|
-
CLOUDANT_APIKEY=<apikey>
|
|
198
|
-
```
|
|
199
|
-
|
|
200
|
-
##### IAM Trusted profile (container) authentication
|
|
201
|
-
|
|
202
|
-
For Cloudant *IAM Trusted profile compute resource container authentication*, set the following environmental variables by
|
|
203
|
-
replacing the `<url>` and `<id>` with your values. There is no need to set
|
|
204
|
-
`CLOUDANT_AUTH_TYPE` to `CONTAINER` because it is the default.
|
|
205
|
-
|
|
206
|
-
```bash
|
|
207
|
-
CLOUDANT_URL=<url>
|
|
208
|
-
CLOUDANT_IAM_PROFILE_ID=<id>
|
|
209
|
-
```
|
|
210
|
-
|
|
211
|
-
Alternatives to `CLOUDANT_IAM_PROFILE_ID`:
|
|
212
|
-
* `CLOUDANT_IAM_PROFILE_NAME`
|
|
213
|
-
|
|
214
|
-
##### IAM Trusted profile (VPC) authentication
|
|
215
|
-
|
|
216
|
-
For Cloudant *IAM Trusted profile compute resource vpc authentication*, set the following environmental variables by
|
|
217
|
-
replacing the `<url>` and `<id>` with your values.
|
|
218
|
-
|
|
219
|
-
```bash
|
|
220
|
-
CLOUDANT_AUTH_TYPE=VPC
|
|
221
|
-
CLOUDANT_URL=<url>
|
|
222
|
-
CLOUDANT_IAM_PROFILE_ID=<id>
|
|
223
|
-
```
|
|
224
|
-
|
|
225
|
-
Alternatives to `CLOUDANT_IAM_PROFILE_ID`:
|
|
226
|
-
* `CLOUDANT_IAM_PROFILE_CRN`
|
|
227
|
-
* No profile information (uses the default trusted profile linked to the compute resource)
|
|
228
|
-
|
|
229
|
-
##### IAM Trusted profile (assume identity) authentication
|
|
230
|
-
|
|
231
|
-
For Cloudant *IAM Trusted profile assume authentication*, set the following environmental variables by
|
|
232
|
-
replacing the `<url>` and `<id>` with your values.
|
|
233
|
-
|
|
234
|
-
```bash
|
|
235
|
-
CLOUDANT_AUTH_TYPE=IAMASSUME
|
|
236
|
-
CLOUDANT_URL=<url>
|
|
237
|
-
CLOUDANT_IAM_PROFILE_ID=<id>
|
|
115
|
+
Quick start for Cloudant with an IAM API key:
|
|
116
|
+
```sh
|
|
117
|
+
CLOUDANT_URL=https://~replaceWithYourUniqueHost~.cloudantnosqldb.appdomain.cloud # use your own Cloudant public or private URL # use your own Cloudant public or private URL
|
|
118
|
+
CLOUDANT_APIKEY=a1b2c3d4e5f6f1g4h7j3k6l9m2p5q8s1t4v7x0z3 # use your own IAM API key
|
|
238
119
|
```
|
|
239
120
|
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
* `CLOUDANT_IAM_PROFILE_NAME` *and* `CLOUDANT_IAM_ACCOUNT_ID` (ID of the account that contains the named trusted profile)
|
|
243
|
-
|
|
244
|
-
##### Session cookie authentication
|
|
245
|
-
|
|
246
|
-
For `COUCHDB_SESSION` authentication, set the following environmental variables
|
|
247
|
-
by replacing the `<url>`, `<username>` and `<password>` with your proper
|
|
248
|
-
[service credentials](https://cloud.ibm.com/docs/Cloudant?topic=Cloudant-locating-your-service-credentials).
|
|
249
|
-
|
|
250
|
-
```bash
|
|
121
|
+
Quick start for Apache CouchDB with a username/password session:
|
|
122
|
+
```sh
|
|
251
123
|
CLOUDANT_AUTH_TYPE=COUCHDB_SESSION
|
|
252
|
-
CLOUDANT_URL
|
|
253
|
-
CLOUDANT_USERNAME
|
|
254
|
-
CLOUDANT_PASSWORD
|
|
124
|
+
CLOUDANT_URL=http://~replaceWithYourUniqueHost~.example:5984 # use your CouchDB URL
|
|
125
|
+
CLOUDANT_USERNAME=username # replace with your username
|
|
126
|
+
CLOUDANT_PASSWORD=password # replace with your password
|
|
255
127
|
```
|
|
256
128
|
|
|
257
|
-
#### Authentication with external configuration
|
|
258
|
-
|
|
259
|
-
For more information about using an external configuration file, see the related documentation in
|
|
260
|
-
[Cloudant API docs](https://cloud.ibm.com/apidocs/cloudant?code=node#authentication-with-external-configuration),
|
|
261
|
-
or the
|
|
262
|
-
[general SDK usage information](https://github.com/IBM/ibm-cloud-sdk-common#using-external-configuration).
|
|
263
|
-
|
|
264
|
-
#### Programmatic authentication
|
|
265
|
-
|
|
266
|
-
To learn more about how to use programmatic authentication, see the related
|
|
267
|
-
documentation in the
|
|
268
|
-
[Cloudant API docs](https://cloud.ibm.com/apidocs/cloudant?code=node#programmatic-authentication)
|
|
269
|
-
or in the
|
|
270
|
-
[Node.js SDK Core document](https://github.com/IBM/node-sdk-core/blob/main/Authentication.md) about authentication.
|
|
271
|
-
|
|
272
129
|
### Automatic retries
|
|
273
130
|
|
|
274
131
|
The SDK supports a generalized retry feature that can automatically retry on common errors.
|
|
@@ -284,671 +141,23 @@ The [request timeout](https://github.com/IBM/ibm-cloud-sdk-common#configuring-re
|
|
|
284
141
|
|
|
285
142
|
### Code examples
|
|
286
143
|
|
|
287
|
-
|
|
288
|
-
[authenticate with the environment variables](#authentication-with-environment-variables).
|
|
289
|
-
|
|
290
|
-
#### 1. Create a database and add a document
|
|
291
|
-
|
|
292
|
-
**Note:** This example code assumes that `orders` database does not exist in your account.
|
|
293
|
-
|
|
294
|
-
This example code creates `orders` database and adds a new document "example"
|
|
295
|
-
into it. To connect, you must set your environment variables with
|
|
296
|
-
the *service url*, *authentication type* and *authentication credentials*
|
|
297
|
-
of your Cloudant service.
|
|
298
|
-
|
|
299
|
-
Cloudant environment variable naming starts with a *service name* prefix that identifies your service.
|
|
300
|
-
By default, this is `CLOUDANT`, see the settings in the
|
|
301
|
-
[authentication with environment variables section](#authentication-with-environment-variables).
|
|
302
|
-
|
|
303
|
-
If you would like to rename your Cloudant service from `CLOUDANT`,
|
|
304
|
-
you must use your defined service name as the prefix for all Cloudant related environment variables.
|
|
305
|
-
|
|
306
|
-
Once the environment variables are set, you can try out the code examples.
|
|
307
|
-
|
|
308
|
-
<details open>
|
|
309
|
-
<summary>TypeScript:</summary>
|
|
310
|
-
|
|
311
|
-
```ts
|
|
312
|
-
import { CloudantV1 } from '@ibm-cloud/cloudant';
|
|
313
|
-
```
|
|
314
|
-
|
|
315
|
-
```ts
|
|
316
|
-
interface OrderDocument extends CloudantV1.Document {
|
|
317
|
-
name?: string;
|
|
318
|
-
joined?: string;
|
|
319
|
-
_id: string;
|
|
320
|
-
_rev?: string;
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
// 1. Create a client with `CLOUDANT` default service name ======================
|
|
324
|
-
const client = CloudantV1.newInstance({});
|
|
325
|
-
|
|
326
|
-
// 2. Create a database =========================================================
|
|
327
|
-
const exampleDbName = 'orders';
|
|
328
|
-
|
|
329
|
-
// Try to create database if it doesn't exist
|
|
330
|
-
const createDb = client
|
|
331
|
-
.putDatabase({ db: exampleDbName })
|
|
332
|
-
.then((putDatabaseResult) => {
|
|
333
|
-
if (putDatabaseResult.result.ok) {
|
|
334
|
-
console.log(`"${exampleDbName}" database created."`);
|
|
335
|
-
}
|
|
336
|
-
})
|
|
337
|
-
.catch((err) => {
|
|
338
|
-
if (err.code === 412) {
|
|
339
|
-
console.log(
|
|
340
|
-
`Cannot create "${exampleDbName}" database, it already exists.`
|
|
341
|
-
);
|
|
342
|
-
}
|
|
343
|
-
});
|
|
344
|
-
|
|
345
|
-
// 3. Create a document =========================================================
|
|
346
|
-
// Create a document object with "example" id
|
|
347
|
-
const exampleDocId = 'example';
|
|
348
|
-
|
|
349
|
-
// Setting `_id` for the document is optional when postDocument function is used for CREATE.
|
|
350
|
-
// When `_id` is not provided the server will generate one for your document.
|
|
351
|
-
const exampleDocument: OrderDocument = { _id: exampleDocId };
|
|
352
|
-
|
|
353
|
-
// Add "name" and "joined" fields to the document
|
|
354
|
-
exampleDocument.name = 'Bob Smith';
|
|
355
|
-
exampleDocument.joined = '2019-01-24T10:42:59.000Z';
|
|
356
|
-
|
|
357
|
-
// Save the document in the database with "postDocument" function
|
|
358
|
-
createDb.then(() => {
|
|
359
|
-
client
|
|
360
|
-
.postDocument({
|
|
361
|
-
db: exampleDbName,
|
|
362
|
-
document: exampleDocument,
|
|
363
|
-
})
|
|
364
|
-
// ==========================================================================
|
|
365
|
-
// Note: saving the document can also be done with the "putDocument"
|
|
366
|
-
// function. In this case `docId` is required for a CREATE operation:
|
|
367
|
-
/*
|
|
368
|
-
.putDocument({
|
|
369
|
-
db: exampleDbName,
|
|
370
|
-
docId: exampleDocId,
|
|
371
|
-
document: exampleDocument,
|
|
372
|
-
})
|
|
373
|
-
*/
|
|
374
|
-
// ==========================================================================
|
|
375
|
-
.then((createDocumentResponse) => {
|
|
376
|
-
// Keeping track of the revision number of the document object
|
|
377
|
-
// is necessary for further UPDATE/DELETE operations:
|
|
378
|
-
exampleDocument._rev = createDocumentResponse.result.rev;
|
|
379
|
-
console.log(
|
|
380
|
-
'You have created the document:\n' +
|
|
381
|
-
JSON.stringify(exampleDocument, null, 2)
|
|
382
|
-
);
|
|
383
|
-
});
|
|
384
|
-
});
|
|
385
|
-
```
|
|
386
|
-
|
|
387
|
-
</details>
|
|
388
|
-
|
|
389
|
-
<details>
|
|
390
|
-
<summary>JavaScript:</summary>
|
|
144
|
+
Quick start example to list all databases (assumes environment variable [authentication](#authentication)):
|
|
391
145
|
|
|
392
146
|
```js
|
|
147
|
+
// section: code
|
|
393
148
|
import { CloudantV1 } from '@ibm-cloud/cloudant';
|
|
394
|
-
```
|
|
395
|
-
|
|
396
|
-
```js
|
|
397
|
-
const createDbAndDoc = async () => {
|
|
398
|
-
// 1. Create a client with `CLOUDANT` default service name ====================
|
|
399
|
-
const client = CloudantV1.newInstance({});
|
|
400
|
-
|
|
401
|
-
// 2. Create a database =======================================================
|
|
402
|
-
const exampleDbName = 'orders';
|
|
403
|
-
|
|
404
|
-
// Try to create database if it doesn't exist
|
|
405
|
-
try {
|
|
406
|
-
const putDatabaseResult = (
|
|
407
|
-
await client.putDatabase({
|
|
408
|
-
db: exampleDbName,
|
|
409
|
-
})
|
|
410
|
-
).result;
|
|
411
|
-
if (putDatabaseResult.ok) {
|
|
412
|
-
console.log(`"${exampleDbName}" database created.`);
|
|
413
|
-
}
|
|
414
|
-
} catch (err) {
|
|
415
|
-
if (err.code === 412) {
|
|
416
|
-
console.log(
|
|
417
|
-
`Cannot create "${exampleDbName}" database, it already exists.`
|
|
418
|
-
);
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
// 3. Create a document =======================================================
|
|
423
|
-
// Create a document object with "example" id
|
|
424
|
-
const exampleDocId = 'example';
|
|
425
|
-
|
|
426
|
-
// Setting `_id` for the document is optional when "postDocument" function is used for CREATE.
|
|
427
|
-
// When `_id` is not provided the server will generate one for your document.
|
|
428
|
-
const exampleDocument = { _id: exampleDocId };
|
|
429
|
-
|
|
430
|
-
// Add "name" and "joined" fields to the document
|
|
431
|
-
exampleDocument['name'] = 'Bob Smith';
|
|
432
|
-
exampleDocument.joined = '2019-01-24T10:42:59.000Z';
|
|
433
|
-
|
|
434
|
-
// Save the document in the database with "postDocument" function
|
|
435
|
-
const createDocumentResponse = await client.postDocument({
|
|
436
|
-
db: exampleDbName,
|
|
437
|
-
document: exampleDocument,
|
|
438
|
-
});
|
|
439
|
-
|
|
440
|
-
// ==========================================================================
|
|
441
|
-
// Note: saving the document can also be done with the "putDocument"
|
|
442
|
-
// function. In this case `docId` is required for a CREATE operation:
|
|
443
|
-
/* const createDocumentResponse = await client.putDocument({
|
|
444
|
-
db: exampleDbName,
|
|
445
|
-
docId: exampleDocId,
|
|
446
|
-
document: exampleDocument,
|
|
447
|
-
}); */
|
|
448
|
-
// ==========================================================================
|
|
449
|
-
|
|
450
|
-
// Keeping track of the revision number of the document object
|
|
451
|
-
// is necessary for further UPDATE/DELETE operations:
|
|
452
|
-
exampleDocument._rev = createDocumentResponse.result.rev;
|
|
453
|
-
console.log(
|
|
454
|
-
'You have created the document:\n' +
|
|
455
|
-
JSON.stringify(exampleDocument, null, 2)
|
|
456
|
-
);
|
|
457
|
-
};
|
|
458
|
-
|
|
459
|
-
if (require.main === module) {
|
|
460
|
-
createDbAndDoc();
|
|
461
|
-
}
|
|
462
|
-
```
|
|
463
|
-
|
|
464
|
-
</details>
|
|
465
|
-
|
|
466
|
-
When you run the code, you see a result similar to the following output.
|
|
467
|
-
|
|
468
|
-
```text
|
|
469
|
-
"orders" database created.
|
|
470
|
-
You have created the document:
|
|
471
|
-
{
|
|
472
|
-
"_id": "example",
|
|
473
|
-
"name": "Bob Smith",
|
|
474
|
-
"joined": "2019-01-24T10:42:59.000Z",
|
|
475
|
-
"_rev": "1-1b403633540686aa32d013fda9041a5d"
|
|
476
|
-
}
|
|
477
|
-
```
|
|
478
|
-
|
|
479
|
-
#### 2. Retrieve information from an existing database
|
|
480
|
-
|
|
481
|
-
**Note**: This example code assumes that you have created both the `orders`
|
|
482
|
-
database and the `example` document by
|
|
483
|
-
[running the previous example code](#1-create-a-database-and-add-a-document)
|
|
484
|
-
successfully. Otherwise, the following error message occurs, "Cannot delete document because either 'orders'
|
|
485
|
-
database or 'example' document was not found."
|
|
486
|
-
|
|
487
|
-
<details>
|
|
488
|
-
<summary>Gather database information example</summary>
|
|
489
|
-
|
|
490
|
-
<details open>
|
|
491
|
-
<summary>TypeScript:</summary>
|
|
492
|
-
|
|
493
|
-
```ts
|
|
494
|
-
import { CloudantV1 } from '@ibm-cloud/cloudant';
|
|
495
|
-
```
|
|
496
|
-
|
|
497
|
-
```ts
|
|
498
|
-
// 1. Create a client with `CLOUDANT` default service name =====================
|
|
499
|
-
const client = CloudantV1.newInstance({});
|
|
500
|
-
|
|
501
|
-
// 2. Get server information ====================================================
|
|
502
|
-
// call service without parameters:
|
|
503
|
-
client.getServerInformation().then((serverInformation) => {
|
|
504
|
-
const { version } = serverInformation.result;
|
|
505
|
-
console.log(`Server version ${version}`);
|
|
506
|
-
});
|
|
507
|
-
|
|
508
|
-
// 3. Get database information for "orders" ===================================
|
|
509
|
-
const dbName = 'orders';
|
|
510
149
|
|
|
511
|
-
|
|
512
|
-
client.getDatabaseInformation({ db: dbName }).then((dbInfo) => {
|
|
513
|
-
const documentCount = dbInfo.result.docCount;
|
|
514
|
-
const dbNameResult = dbInfo.result.dbName;
|
|
150
|
+
const service = CloudantV1.newInstance({});
|
|
515
151
|
|
|
516
|
-
|
|
517
|
-
console.log(
|
|
518
|
-
`Document count in "${dbNameResult}" database is ${documentCount}.`
|
|
519
|
-
);
|
|
152
|
+
service.getAllDbs().then(response => {
|
|
153
|
+
console.log(response.result);
|
|
520
154
|
});
|
|
521
|
-
|
|
522
|
-
// 5. Get "example" document out of the database by document id =====================
|
|
523
|
-
const getDocParams: CloudantV1.GetDocumentParams = {
|
|
524
|
-
db: dbName,
|
|
525
|
-
docId: 'example',
|
|
526
|
-
};
|
|
527
|
-
|
|
528
|
-
// call service with predefined parameters:
|
|
529
|
-
client.getDocument(getDocParams).then((documentExample) => {
|
|
530
|
-
// result object is defined as a Document here:
|
|
531
|
-
const { result } = documentExample;
|
|
532
|
-
console.log(
|
|
533
|
-
`Document retrieved from database:\n${JSON.stringify(result, null, 2)}`
|
|
534
|
-
);
|
|
535
|
-
});
|
|
536
|
-
```
|
|
537
|
-
|
|
538
|
-
</details>
|
|
539
|
-
|
|
540
|
-
<details>
|
|
541
|
-
<summary>JavaScript:</summary>
|
|
542
|
-
|
|
543
|
-
```js
|
|
544
|
-
import { CloudantV1 } from '@ibm-cloud/cloudant';
|
|
545
|
-
```
|
|
546
|
-
|
|
547
|
-
```js
|
|
548
|
-
const getInfoFromExistingDatabase = async () => {
|
|
549
|
-
// 1. Create a client with `CLOUDANT` default service name ===================
|
|
550
|
-
const client = CloudantV1.newInstance({});
|
|
551
|
-
|
|
552
|
-
// 2. Get server information ==================================================
|
|
553
|
-
// call service without parameters:
|
|
554
|
-
const { version } = (await client.getServerInformation()).result;
|
|
555
|
-
console.log(`Server version ${version}`);
|
|
556
|
-
|
|
557
|
-
// 3. Get database information for "orders" =================================
|
|
558
|
-
const dbName = 'orders';
|
|
559
|
-
|
|
560
|
-
// call service with embedded parameters:
|
|
561
|
-
const dbInfo = await client.getDatabaseInformation({ db: dbName });
|
|
562
|
-
const documentCount = dbInfo.result.docCount;
|
|
563
|
-
const dbNameResult = dbInfo.result.dbName;
|
|
564
|
-
|
|
565
|
-
// 4. Show document count in database =========================================
|
|
566
|
-
console.log(
|
|
567
|
-
`Document count in "${dbNameResult}" database is ${documentCount}.`
|
|
568
|
-
);
|
|
569
|
-
|
|
570
|
-
// 5. Get "example" document out of the database by document id ===================
|
|
571
|
-
const getDocParams = { db: dbName, docId: 'example' };
|
|
572
|
-
|
|
573
|
-
// call service with predefined parameters:
|
|
574
|
-
const documentExample = await client.getDocument(getDocParams);
|
|
575
|
-
|
|
576
|
-
// result object is defined as a Document here:
|
|
577
|
-
const { result } = documentExample;
|
|
578
|
-
|
|
579
|
-
console.log(
|
|
580
|
-
`Document retrieved from database:\n${JSON.stringify(result, null, 2)}`
|
|
581
|
-
);
|
|
582
|
-
};
|
|
583
|
-
|
|
584
|
-
if (require.main === module) {
|
|
585
|
-
getInfoFromExistingDatabase();
|
|
586
|
-
}
|
|
587
|
-
```
|
|
588
|
-
|
|
589
|
-
</details>
|
|
590
|
-
|
|
591
|
-
</details>
|
|
592
|
-
When you run the code, you see a result similar to the following output.
|
|
593
|
-
|
|
594
|
-
```text
|
|
595
|
-
Server version 3.2.1
|
|
596
|
-
Document count in "orders" database is 1.
|
|
597
|
-
Document retrieved from database:
|
|
598
|
-
{
|
|
599
|
-
"_id": "example",
|
|
600
|
-
"_rev": "1-1b403633540686aa32d013fda9041a5d",
|
|
601
|
-
"name": "Bob Smith",
|
|
602
|
-
"joined": "2019-01-24T10:42:59.000Z"
|
|
603
|
-
}
|
|
604
|
-
```
|
|
605
|
-
|
|
606
|
-
#### 3. Update your previously created document
|
|
607
|
-
|
|
608
|
-
**Note**: This example code assumes that you have created both the `orders`
|
|
609
|
-
database and the `example` document by
|
|
610
|
-
[running the previous example code](#1-create-a-database-and-add-a-document)
|
|
611
|
-
successfully. Otherwise, the following error message occurs, "Cannot update document because either 'orders'
|
|
612
|
-
database or 'example' document was not found."
|
|
613
|
-
|
|
614
|
-
<details>
|
|
615
|
-
<summary>Update code example</summary>
|
|
616
|
-
|
|
617
|
-
<details open>
|
|
618
|
-
<summary>TypeScript:</summary>
|
|
619
|
-
|
|
620
|
-
```ts
|
|
621
|
-
import { CloudantV1 } from '@ibm-cloud/cloudant';
|
|
622
|
-
```
|
|
623
|
-
|
|
624
|
-
```ts
|
|
625
|
-
interface OrderDocument extends CloudantV1.Document {
|
|
626
|
-
address?: string;
|
|
627
|
-
joined?: string;
|
|
628
|
-
_id?: string;
|
|
629
|
-
_rev?: string;
|
|
630
|
-
}
|
|
631
|
-
|
|
632
|
-
// 1. Create a client with `CLOUDANT` default service name ======================
|
|
633
|
-
const client = CloudantV1.newInstance({});
|
|
634
|
-
// 2. Update the document =======================================================
|
|
635
|
-
// Set the options to get the document out of the database if it exists
|
|
636
|
-
const exampleDbName = 'orders';
|
|
637
|
-
|
|
638
|
-
// Try to get the document if it previously existed in the database
|
|
639
|
-
const getDocParams: CloudantV1.GetDocumentParams = {
|
|
640
|
-
docId: 'example',
|
|
641
|
-
db: exampleDbName,
|
|
642
|
-
};
|
|
643
|
-
|
|
644
|
-
// ==============================================================================
|
|
645
|
-
// Note : for response byte stream use:
|
|
646
|
-
/*
|
|
647
|
-
const getdocAsStreamParam: CloudantV1.GetDocumentAsStreamParams = {
|
|
648
|
-
docId: 'example',
|
|
649
|
-
db: exampleDbName,
|
|
650
|
-
};
|
|
651
|
-
client
|
|
652
|
-
.getDocumentAsStream(getdocAsStreamParam)
|
|
653
|
-
.then((documentAsByteStream) => {...});
|
|
654
|
-
*/
|
|
655
|
-
// ==============================================================================
|
|
656
|
-
|
|
657
|
-
client
|
|
658
|
-
.getDocument(getDocParams)
|
|
659
|
-
.then((docResult) => {
|
|
660
|
-
// using OrderDocument on getDocument result:
|
|
661
|
-
const document: OrderDocument = docResult.result;
|
|
662
|
-
|
|
663
|
-
// Add Bob Smith's address to the document
|
|
664
|
-
document.address = '19 Front Street, Darlington, DL5 1TY';
|
|
665
|
-
|
|
666
|
-
// Remove the joined property from document object
|
|
667
|
-
delete document.joined;
|
|
668
|
-
|
|
669
|
-
// Update the document in the database
|
|
670
|
-
client
|
|
671
|
-
.postDocument({ db: exampleDbName, document })
|
|
672
|
-
// ========================================================================
|
|
673
|
-
// Note 1: for request byte stream use:
|
|
674
|
-
// .postDocument(
|
|
675
|
-
// {db: exampleDbName, document: documentAsByteStream}
|
|
676
|
-
// )
|
|
677
|
-
// ========================================================================
|
|
678
|
-
|
|
679
|
-
// ========================================================================
|
|
680
|
-
// Note 2: updating the document can also be done with the "putDocument" function.
|
|
681
|
-
// `docId` and `rev` are required for an UPDATE operation,
|
|
682
|
-
// but `rev` can be provided in the document object as `_rev` too:
|
|
683
|
-
/*
|
|
684
|
-
.putDocument({
|
|
685
|
-
db: exampleDbName,
|
|
686
|
-
docId: document._id, // docId is a required parameter
|
|
687
|
-
rev: document._rev,
|
|
688
|
-
document, // _rev in the document object CAN replace above `rev` parameter
|
|
689
|
-
})
|
|
690
|
-
*/
|
|
691
|
-
// ========================================================================
|
|
692
|
-
.then((res) => {
|
|
693
|
-
// Keeping track of the latest revision number of the document object
|
|
694
|
-
// is necessary for further UPDATE/DELETE operations:
|
|
695
|
-
document._rev = res.result.rev;
|
|
696
|
-
console.log(
|
|
697
|
-
`You have updated the document:\n${JSON.stringify(document, null, 2)}`
|
|
698
|
-
);
|
|
699
|
-
});
|
|
700
|
-
})
|
|
701
|
-
.catch((err) => {
|
|
702
|
-
if (err.code === 404) {
|
|
703
|
-
console.log(
|
|
704
|
-
`Cannot update document because either "${exampleDbName}" database or the "example" ` +
|
|
705
|
-
`document was not found.`
|
|
706
|
-
);
|
|
707
|
-
}
|
|
708
|
-
});
|
|
709
|
-
```
|
|
710
|
-
|
|
711
|
-
</details>
|
|
712
|
-
|
|
713
|
-
<details>
|
|
714
|
-
<summary>JavaScript:</summary>
|
|
715
|
-
|
|
716
|
-
```js
|
|
717
|
-
import { CloudantV1 } from '@ibm-cloud/cloudant';
|
|
718
|
-
```
|
|
719
|
-
|
|
720
|
-
```js
|
|
721
|
-
const updateDoc = async () => {
|
|
722
|
-
// 1. Create a client with `CLOUDANT` default service name ====================
|
|
723
|
-
const client = CloudantV1.newInstance({});
|
|
724
|
-
// 2. Update the document =====================================================
|
|
725
|
-
// Set the options to get the document out of the database if it exists
|
|
726
|
-
const exampleDbName = 'orders';
|
|
727
|
-
|
|
728
|
-
// Try to get the document if it previously existed in the database
|
|
729
|
-
try {
|
|
730
|
-
const document = (
|
|
731
|
-
await client.getDocument({
|
|
732
|
-
docId: 'example',
|
|
733
|
-
db: exampleDbName,
|
|
734
|
-
})
|
|
735
|
-
).result;
|
|
736
|
-
|
|
737
|
-
// ==========================================================================
|
|
738
|
-
// Note: for response byte stream use:
|
|
739
|
-
/*
|
|
740
|
-
const documentAsByteStream = (
|
|
741
|
-
await client.getDocumentAsStream({
|
|
742
|
-
docId: 'example',
|
|
743
|
-
db: exampleDbName,
|
|
744
|
-
})
|
|
745
|
-
).result;
|
|
746
|
-
*/
|
|
747
|
-
// ==========================================================================
|
|
748
|
-
|
|
749
|
-
// Add Bob Smith's address to the document
|
|
750
|
-
document.address = '19 Front Street, Darlington, DL5 1TY';
|
|
751
|
-
|
|
752
|
-
// Remove the joined property from document object
|
|
753
|
-
delete document['joined'];
|
|
754
|
-
|
|
755
|
-
// Keeping track of the latest revision number of the document object
|
|
756
|
-
// is necessary for further UPDATE/DELETE operations:
|
|
757
|
-
document._rev = (
|
|
758
|
-
await client.postDocument({
|
|
759
|
-
db: exampleDbName,
|
|
760
|
-
document, // _id and _rev MUST be inside the document object
|
|
761
|
-
})
|
|
762
|
-
).result.rev;
|
|
763
|
-
|
|
764
|
-
// ==========================================================================
|
|
765
|
-
// Note 1: for request byte stream use:
|
|
766
|
-
/*
|
|
767
|
-
document._rev = (
|
|
768
|
-
await client.postDocument({
|
|
769
|
-
db: exampleDbName,
|
|
770
|
-
document: documentAsByteStream,
|
|
771
|
-
})
|
|
772
|
-
).result.rev;
|
|
773
|
-
*/
|
|
774
|
-
// ==========================================================================
|
|
775
|
-
|
|
776
|
-
// ==========================================================================
|
|
777
|
-
// Note 2: updating the document can also be done with the "putDocument" function.
|
|
778
|
-
// `docId` and `rev` are required for an UPDATE operation,
|
|
779
|
-
// but `rev` can be provided in the document object as `_rev` too:
|
|
780
|
-
/*
|
|
781
|
-
document._rev = (
|
|
782
|
-
await client.putDocument({
|
|
783
|
-
db: exampleDbName,
|
|
784
|
-
docId: document._id, // docId is a required parameter
|
|
785
|
-
rev: document._rev,
|
|
786
|
-
document // _rev in the document object CAN replace above `rev` parameter
|
|
787
|
-
})
|
|
788
|
-
).result.rev;
|
|
789
|
-
*/
|
|
790
|
-
// ==========================================================================
|
|
791
|
-
|
|
792
|
-
console.log(
|
|
793
|
-
`You have updated the document:\n${JSON.stringify(document, null, 2)}`
|
|
794
|
-
);
|
|
795
|
-
} catch (err) {
|
|
796
|
-
if (err.code === 404) {
|
|
797
|
-
console.log(
|
|
798
|
-
`Cannot update document because either "${exampleDbName}" database or the "example" ` +
|
|
799
|
-
`document was not found.`
|
|
800
|
-
);
|
|
801
|
-
}
|
|
802
|
-
}
|
|
803
|
-
};
|
|
804
|
-
|
|
805
|
-
if (require.main === module) {
|
|
806
|
-
updateDoc();
|
|
807
|
-
}
|
|
808
|
-
```
|
|
809
|
-
|
|
810
|
-
</details>
|
|
811
|
-
|
|
812
|
-
</details>
|
|
813
|
-
When you run the code, you see a result similar to the following output.
|
|
814
|
-
|
|
815
|
-
```text
|
|
816
|
-
You have updated the document:
|
|
817
|
-
{
|
|
818
|
-
"_id": "example",
|
|
819
|
-
"_rev": "2-4e2178e85cffb32d38ba4e451f6ca376",
|
|
820
|
-
"name": "Bob Smith",
|
|
821
|
-
"address": "19 Front Street, Darlington, DL5 1TY"
|
|
822
|
-
}
|
|
823
|
-
```
|
|
824
|
-
|
|
825
|
-
#### 4. Delete your previously created document
|
|
826
|
-
|
|
827
|
-
**Note**: This example code assumes that you have created both the `orders`
|
|
828
|
-
database and the `example` document by
|
|
829
|
-
[running the previous example code](#1-create-a-database-and-add-a-document)
|
|
830
|
-
successfully. Otherwise, the following error message occurs, "Cannot delete document because either 'orders'
|
|
831
|
-
database or 'example' document was not found."
|
|
832
|
-
|
|
833
|
-
<details>
|
|
834
|
-
<summary>Delete code example</summary>
|
|
835
|
-
|
|
836
|
-
<details open>
|
|
837
|
-
<summary>TypeScript:</summary>
|
|
838
|
-
|
|
839
|
-
```ts
|
|
840
|
-
import { CloudantV1 } from '@ibm-cloud/cloudant';
|
|
841
|
-
```
|
|
842
|
-
|
|
843
|
-
```ts
|
|
844
|
-
interface OrderDocument extends CloudantV1.Document {
|
|
845
|
-
name?: string;
|
|
846
|
-
address?: string;
|
|
847
|
-
joined?: string;
|
|
848
|
-
_id?: string;
|
|
849
|
-
_rev?: string;
|
|
850
|
-
}
|
|
851
|
-
|
|
852
|
-
// 1. Create a client with `CLOUDANT` default service name ======================
|
|
853
|
-
const client = CloudantV1.newInstance({});
|
|
854
|
-
|
|
855
|
-
// 2. Delete the document =======================================================
|
|
856
|
-
// Set the options to get the document out of the database if it exists
|
|
857
|
-
const exampleDbName = 'orders';
|
|
858
|
-
const exampleDocId = 'example';
|
|
859
|
-
|
|
860
|
-
// Try to get the document if it previously existed in the database
|
|
861
|
-
const getDocParams: CloudantV1.GetDocumentParams = {
|
|
862
|
-
docId: exampleDocId,
|
|
863
|
-
db: exampleDbName,
|
|
864
|
-
};
|
|
865
|
-
|
|
866
|
-
client
|
|
867
|
-
.getDocument(getDocParams)
|
|
868
|
-
.then((docResult) => {
|
|
869
|
-
const document: OrderDocument = docResult.result;
|
|
870
|
-
|
|
871
|
-
client
|
|
872
|
-
.deleteDocument({
|
|
873
|
-
db: exampleDbName,
|
|
874
|
-
docId: document._id, // `docId` is required for DELETE
|
|
875
|
-
rev: document._rev, // `rev` is required for DELETE
|
|
876
|
-
})
|
|
877
|
-
.then(() => {
|
|
878
|
-
console.log('You have deleted the document.');
|
|
879
|
-
});
|
|
880
|
-
})
|
|
881
|
-
.catch((err) => {
|
|
882
|
-
if (err.code === 404) {
|
|
883
|
-
console.log(
|
|
884
|
-
`Cannot delete document because either "${exampleDbName}" database or the "example" ` +
|
|
885
|
-
`document was not found.`
|
|
886
|
-
);
|
|
887
|
-
}
|
|
888
|
-
});
|
|
889
|
-
```
|
|
890
|
-
|
|
891
|
-
</details>
|
|
892
|
-
|
|
893
|
-
<details>
|
|
894
|
-
<summary>JavaScript:</summary>
|
|
895
|
-
|
|
896
|
-
```js
|
|
897
|
-
import { CloudantV1 } from '@ibm-cloud/cloudant';
|
|
898
|
-
```
|
|
899
|
-
|
|
900
|
-
```js
|
|
901
|
-
const deleteDoc = async () => {
|
|
902
|
-
// 1. Create a client with `CLOUDANT` default service name ====================
|
|
903
|
-
const client = CloudantV1.newInstance({});
|
|
904
|
-
|
|
905
|
-
// 2. Delete the document =====================================================
|
|
906
|
-
// Set the options to get the document out of the database if it exists
|
|
907
|
-
const exampleDbName = 'orders';
|
|
908
|
-
const exampleDocId = 'example';
|
|
909
|
-
|
|
910
|
-
// Try to get the document if it previously existed in the database
|
|
911
|
-
try {
|
|
912
|
-
const document = (
|
|
913
|
-
await client.getDocument({
|
|
914
|
-
docId: exampleDocId,
|
|
915
|
-
db: exampleDbName,
|
|
916
|
-
})
|
|
917
|
-
).result;
|
|
918
|
-
|
|
919
|
-
await client.deleteDocument({
|
|
920
|
-
db: exampleDbName,
|
|
921
|
-
docId: document._id, // `docId` is required for DELETE
|
|
922
|
-
rev: document._rev, // `rev` is required for DELETE
|
|
923
|
-
});
|
|
924
|
-
console.log('You have deleted the document.');
|
|
925
|
-
} catch (err) {
|
|
926
|
-
if (err.code === 404) {
|
|
927
|
-
console.log(
|
|
928
|
-
`Cannot delete document because either "${exampleDbName}" database or the "example" ` +
|
|
929
|
-
`document was not found.`
|
|
930
|
-
);
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
};
|
|
934
|
-
|
|
935
|
-
if (require.main === module) {
|
|
936
|
-
deleteDoc();
|
|
937
|
-
}
|
|
938
155
|
```
|
|
939
156
|
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
</details>
|
|
943
|
-
When you run the code, you see the following output.
|
|
157
|
+
[More tutorial examples](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.9/docs/Examples.md) for creating a database
|
|
158
|
+
and document create, read, update and delete operations.
|
|
944
159
|
|
|
945
|
-
|
|
946
|
-
You have deleted the document.
|
|
947
|
-
```
|
|
948
|
-
|
|
949
|
-
#### Further code examples
|
|
950
|
-
|
|
951
|
-
For a complete list of code examples, see the [examples directory](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.7/examples#examples-for-node).
|
|
160
|
+
For a complete list of code examples, see the [examples directory](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.9/examples#examples-for-node).
|
|
952
161
|
|
|
953
162
|
### Error handling
|
|
954
163
|
|
|
@@ -972,7 +181,7 @@ Response byte stream is supported in functions with the suffix of `AsStream`.
|
|
|
972
181
|
The returned byte stream allows the response body to be consumed
|
|
973
182
|
without triggering JSON unmarshalling that is typically performed by the SDK.
|
|
974
183
|
|
|
975
|
-
The [update document](#3-update-your-previously-created-document) section
|
|
184
|
+
The [update document](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.9/docs/Examples.md#3-update-your-previously-created-document) section
|
|
976
185
|
contains examples for both request and response byte stream cases.
|
|
977
186
|
|
|
978
187
|
The API reference contains further examples of using byte streams.
|
|
@@ -988,6 +197,7 @@ Expand them to see examples of:
|
|
|
988
197
|
|
|
989
198
|
### Further resources
|
|
990
199
|
|
|
200
|
+
- [Cloudant Node.js SDK feature docs](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.9/docs)
|
|
991
201
|
- [Cloudant API docs](https://cloud.ibm.com/apidocs/cloudant?code=node):
|
|
992
202
|
API reference including usage examples for Cloudant Node.js SDK API.
|
|
993
203
|
- [TypeDoc](https://ibm.github.io/cloudant-node-sdk/):
|
|
@@ -1059,1098 +269,6 @@ To allow CORS requests from the SDK in the browser:
|
|
|
1059
269
|
service.setEnableGzipCompression(false);
|
|
1060
270
|
```
|
|
1061
271
|
|
|
1062
|
-
### Changes feed follower
|
|
1063
|
-
|
|
1064
|
-
#### Introduction
|
|
1065
|
-
|
|
1066
|
-
The SDK provides a changes feed follower utility.
|
|
1067
|
-
This helper utility connects to the `_changes` endpoint and returns the individual change items.
|
|
1068
|
-
It removes some complexity of using the `_changes` endpoint by setting some options automatically
|
|
1069
|
-
and providing error suppression and retries.
|
|
1070
|
-
|
|
1071
|
-
*Tip: the changes feed often does not meet user expectations or assumptions.*
|
|
1072
|
-
|
|
1073
|
-
Consult the [Cloudant changes feed FAQ](https://cloud.ibm.com/docs/Cloudant?topic=Cloudant-faq-using-changes-feed)
|
|
1074
|
-
to get a better understanding of the limitations and suitable use-cases before using the changes feed in your application.
|
|
1075
|
-
|
|
1076
|
-
#### Modes of operation
|
|
1077
|
-
|
|
1078
|
-
There are two modes of operation:
|
|
1079
|
-
* Start mode
|
|
1080
|
-
* Fetches the changes from the supplied `since` sequence (in this mode follower defaults to reading the feed from `now`).
|
|
1081
|
-
* Fetches all available changes and then continues listening for new changes indefinitely unless encountering an end condition.
|
|
1082
|
-
* An example use case for this mode is event driven workloads.
|
|
1083
|
-
* Start one-off mode
|
|
1084
|
-
* Fetches the changes from the supplied `since` sequence (in this mode follower defaults to reading the feed from the beginning).
|
|
1085
|
-
* Fetches all available changes and then stops when either there are no further changes pending or encountering an end condition.
|
|
1086
|
-
* An example use case for this mode is ETL style workloads.
|
|
1087
|
-
|
|
1088
|
-
#### Configuring the changes follower
|
|
1089
|
-
|
|
1090
|
-
The SDK's model of changes feed options is also used to configure the follower.
|
|
1091
|
-
However, a subset of the options used internally by the follower implementation are invalid.
|
|
1092
|
-
Supplying these options when instantiating the follower causes an error.
|
|
1093
|
-
The invalid options are:
|
|
1094
|
-
* `descending`
|
|
1095
|
-
* `feed`
|
|
1096
|
-
* `heartbeat`
|
|
1097
|
-
* `lastEventId` - use `since` instead
|
|
1098
|
-
* `timeout`
|
|
1099
|
-
* Follower permits only the value `_selector` for the `filter` option. This restriction is because selector
|
|
1100
|
-
based filters perform better than JavaScript backed filters. Configuring a non-selector based filter
|
|
1101
|
-
causes the follower to error.
|
|
1102
|
-
|
|
1103
|
-
Note that the `limit` parameter terminates the follower at the given number of changes in either
|
|
1104
|
-
operating mode.
|
|
1105
|
-
|
|
1106
|
-
The changes follower requires the client to have HTTP timeouts of at least 1 minute and errors during
|
|
1107
|
-
instantiation if it is insufficient. The default client configuration has sufficiently long timeouts.
|
|
1108
|
-
|
|
1109
|
-
For use-cases where these configuration limitations are too restrictive then write code to use the SDK's
|
|
1110
|
-
[POST `_changes` API](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.7/examples#postchanges) instead of the follower.
|
|
1111
|
-
|
|
1112
|
-
#### Error suppression
|
|
1113
|
-
|
|
1114
|
-
By default, the changes follower suppresses transient errors indefinitely and attempts to run to completion or listen forever as
|
|
1115
|
-
dictated by the operating mode.
|
|
1116
|
-
For applications where that is not desirable configure the optional error tolerance duration. This controls the time since
|
|
1117
|
-
the last successful response that the follower suppresses transient errors. An example usage is an application grace period
|
|
1118
|
-
before reporting an error and requiring intervention.
|
|
1119
|
-
|
|
1120
|
-
There are some additional points to consider for error suppression:
|
|
1121
|
-
* Errors considered terminal, for example, the database not existing or invalid credentials are never suppressed and error immediately.
|
|
1122
|
-
* The error suppression duration is not guaranteed to fire immediately after lapsing and is a minimum suppression time.
|
|
1123
|
-
* The changes follower backs-off between retries and as such may remain paused for a short while after the transient errors have resolved.
|
|
1124
|
-
* If the underlying SDK client used to initialize the follower also has retries configured then suppression of errors may last
|
|
1125
|
-
significantly longer than the follower's configured error tolerance duration depending on the specific options.
|
|
1126
|
-
|
|
1127
|
-
#### Follower operation
|
|
1128
|
-
|
|
1129
|
-
For both modes:
|
|
1130
|
-
* The end conditions are:
|
|
1131
|
-
* A terminal error (HTTP codes `400`, `401`, `403` `404`).
|
|
1132
|
-
* Transient errors occur for longer than the error tolerance duration. Transient errors are all other HTTP status codes and connection errors.
|
|
1133
|
-
* The number of changes received reaches the configured `limit`.
|
|
1134
|
-
* The application calls stop to terminate the feed early.
|
|
1135
|
-
|
|
1136
|
-
As is true for the `_changes` endpoint change items have *at least once* delivery and callers may receive
|
|
1137
|
-
an individual item multiple times. When using the follower change items may repeat even within a limited
|
|
1138
|
-
number of changes (that is using the `limit` option) this is a minor difference from using `limit` on the HTTP native API.
|
|
1139
|
-
|
|
1140
|
-
The follower is not optimized for some use cases and it is not recommended to use it in cases where:
|
|
1141
|
-
* Setting `include_docs` and larger document sizes (for example > 10 kiB).
|
|
1142
|
-
* The volume of changes is very high (if the rate of changes in the database exceeds the follower's rate of pulling them it can never catch-up).
|
|
1143
|
-
|
|
1144
|
-
In these use-cases use the SDK's [POST `_changes` API](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.7/examples#postchanges)
|
|
1145
|
-
for specific control over the number of change requests made and the content size of the responses.
|
|
1146
|
-
|
|
1147
|
-
#### Checkpoints
|
|
1148
|
-
|
|
1149
|
-
The changes follower does not checkpoint since it has no information about whether the consuming application
|
|
1150
|
-
has processed a change item after delivery. It is the application developer's responsibility
|
|
1151
|
-
to store the sequence IDs to have appropriate checkpoints and to re-initialize the follower with the required
|
|
1152
|
-
`since` value after, for example, the application restarts.
|
|
1153
|
-
|
|
1154
|
-
The frequency and conditions for checkpoints are application specific and some applications may be tolerant
|
|
1155
|
-
of dropped changes. This section provides only general guidance on how to avoid missing changes.
|
|
1156
|
-
|
|
1157
|
-
To guarantee processing of all changes do not persist the sequence ID from a change item until *after*
|
|
1158
|
-
the processing of the change item by the application has completed. As indicated previously change item
|
|
1159
|
-
delivery is *at least once* so application code must be able to handle repeated changes already. It is
|
|
1160
|
-
preferable to restart from an older `since` value and receive changes again than risk missing them.
|
|
1161
|
-
|
|
1162
|
-
The sequence IDs are available on each change item by default. However, the server omits sequence IDs from
|
|
1163
|
-
some change items when using the `seq_interval` configuration option.
|
|
1164
|
-
Infrequent sequence IDs may improve performance by reducing the amount of data transfer and server load,
|
|
1165
|
-
but the tradeoff is repeating more changes if it is necessary to resume the changes follower.
|
|
1166
|
-
|
|
1167
|
-
Take extreme care persisting sequences if choosing to process change items in parallel as there
|
|
1168
|
-
is a considerable risk of missing changes on a restart if the recorded sequence is out of order.
|
|
1169
|
-
|
|
1170
|
-
#### Code examples
|
|
1171
|
-
|
|
1172
|
-
##### Initializing a changes follower
|
|
1173
|
-
<details open>
|
|
1174
|
-
<summary>TypeScript:</summary>
|
|
1175
|
-
|
|
1176
|
-
```ts
|
|
1177
|
-
import { ChangesFollower, CloudantV1 } from '@ibm-cloud/cloudant';
|
|
1178
|
-
import { PostChangesParams } from '@ibm-cloud/cloudant/cloudant/v1';
|
|
1179
|
-
```
|
|
1180
|
-
|
|
1181
|
-
```ts
|
|
1182
|
-
const client = CloudantV1.newInstance({});
|
|
1183
|
-
const changesParams: PostChangesParams = {
|
|
1184
|
-
db: 'example', // Required: the database name.
|
|
1185
|
-
limit: 100, // Optional: return only 100 changes (including duplicates).
|
|
1186
|
-
since: '3-g1AG3...' // Optional: start from this sequence ID (e.g. with a value read from persistent storage).
|
|
1187
|
-
};
|
|
1188
|
-
const errorTolerance: number = 10000; // 10 second duration to suppress transient errors
|
|
1189
|
-
const changesFollower: ChangesFollower = new ChangesFollower(
|
|
1190
|
-
client, // Required: the Cloudant service client instance.
|
|
1191
|
-
changesParams, // Required: changes feed configuration options dict.
|
|
1192
|
-
10000 // Optional: suppress transient errors for at least 10 seconds before terminating.
|
|
1193
|
-
);
|
|
1194
|
-
```
|
|
1195
|
-
|
|
1196
|
-
</details>
|
|
1197
|
-
|
|
1198
|
-
<details>
|
|
1199
|
-
<summary>JavaScript:</summary>
|
|
1200
|
-
|
|
1201
|
-
```js
|
|
1202
|
-
import { ChangesFollower, CloudantV1 } from '@ibm-cloud/cloudant';
|
|
1203
|
-
```
|
|
1204
|
-
|
|
1205
|
-
```js
|
|
1206
|
-
const client = CloudantV1.newInstance();
|
|
1207
|
-
const changesParams = {
|
|
1208
|
-
db: 'example', // Required: the database name.
|
|
1209
|
-
limit: 100, // Optional: return only 100 changes (including duplicates).
|
|
1210
|
-
since: '3-g1AG3...' // Optional: start from this sequence ID (e.g. with a value read from persistent storage).
|
|
1211
|
-
};
|
|
1212
|
-
const changesFollower = new ChangesFollower(
|
|
1213
|
-
client, // Required: the Cloudant service client instance.
|
|
1214
|
-
changesParams, // Required: changes feed configuration options dict.
|
|
1215
|
-
10000 // Optional: suppress transient errors for at least 10 seconds before terminating.
|
|
1216
|
-
);
|
|
1217
|
-
```
|
|
1218
|
-
|
|
1219
|
-
</details>
|
|
1220
|
-
|
|
1221
|
-
##### Starting the changes follower
|
|
1222
|
-
|
|
1223
|
-
###### Start mode for continuous listening
|
|
1224
|
-
<details open>
|
|
1225
|
-
<summary>TypeScript:</summary>
|
|
1226
|
-
|
|
1227
|
-
```ts
|
|
1228
|
-
import { ChangesFollower, CloudantV1, Stream } from '@ibm-cloud/cloudant';
|
|
1229
|
-
import { ChangesResultItem, PostChangesParams } from '@ibm-cloud/cloudant/cloudant/v1';
|
|
1230
|
-
```
|
|
1231
|
-
|
|
1232
|
-
```ts
|
|
1233
|
-
const client = CloudantV1.newInstance({});
|
|
1234
|
-
const changesParams: PostChangesParams = {
|
|
1235
|
-
db: 'example'
|
|
1236
|
-
};
|
|
1237
|
-
const changesFollower: ChangesFollower = new ChangesFollower(client, changesParams);
|
|
1238
|
-
const changesItemsStream: Stream<ChangesResultItem> = changesFollower.start();
|
|
1239
|
-
// Create for-async-loop or pipeline to begin the flow of changes
|
|
1240
|
-
// e.g. pipeline(changesItemsStream, destinationStream).then(() => { ... }).catch((err) => { ... });
|
|
1241
|
-
```
|
|
1242
|
-
|
|
1243
|
-
</details>
|
|
1244
|
-
|
|
1245
|
-
<details>
|
|
1246
|
-
<summary>JavaScript:</summary>
|
|
1247
|
-
|
|
1248
|
-
```js
|
|
1249
|
-
import { ChangesFollower, CloudantV1 } from '@ibm-cloud/cloudant';
|
|
1250
|
-
```
|
|
1251
|
-
|
|
1252
|
-
```js
|
|
1253
|
-
const client = CloudantV1.newInstance();
|
|
1254
|
-
const changesParams = {
|
|
1255
|
-
db: 'example'
|
|
1256
|
-
};
|
|
1257
|
-
const changesFollower = new ChangesFollower(client, changesParams);
|
|
1258
|
-
const changesItemsStream = changesFollower.start();
|
|
1259
|
-
// Create for-async-loop or pipeline to begin the flow of changes
|
|
1260
|
-
// e.g. pipeline(changesItemsStream, destinationStream).then(() => { ... }).catch((err) => { ... });
|
|
1261
|
-
```
|
|
1262
|
-
|
|
1263
|
-
</details>
|
|
1264
|
-
|
|
1265
|
-
###### Start mode for one-off fetching
|
|
1266
|
-
<details open>
|
|
1267
|
-
<summary>TypeScript:</summary>
|
|
1268
|
-
|
|
1269
|
-
```ts
|
|
1270
|
-
import { ChangesFollower, CloudantV1, Stream } from '@ibm-cloud/cloudant';
|
|
1271
|
-
import { ChangesResultItem, PostChangesParams } from '@ibm-cloud/cloudant/cloudant/v1';
|
|
1272
|
-
```
|
|
1273
|
-
|
|
1274
|
-
```ts
|
|
1275
|
-
const client = CloudantV1.newInstance({});
|
|
1276
|
-
const changesParams: PostChangesParams = {
|
|
1277
|
-
db: 'example'
|
|
1278
|
-
};
|
|
1279
|
-
const changesFollower: ChangesFollower = new ChangesFollower(client, changesParams);
|
|
1280
|
-
const changesItemsStream: Stream<ChangesResultItem> = changesFollower.startOneOff();
|
|
1281
|
-
// Create for-async-loop or pipeline to begin the flow of changes
|
|
1282
|
-
// e.g. pipeline(changesItemsStream, destinationStream).then(() => { ... }).catch((err) => { ... });
|
|
1283
|
-
```
|
|
1284
|
-
|
|
1285
|
-
</details>
|
|
1286
|
-
|
|
1287
|
-
<details>
|
|
1288
|
-
<summary>JavaScript:</summary>
|
|
1289
|
-
|
|
1290
|
-
```js
|
|
1291
|
-
import { ChangesFollower, CloudantV1 } from '@ibm-cloud/cloudant';
|
|
1292
|
-
```
|
|
1293
|
-
|
|
1294
|
-
```js
|
|
1295
|
-
const client = CloudantV1.newInstance();
|
|
1296
|
-
const changesParams = {
|
|
1297
|
-
db: 'example'
|
|
1298
|
-
};
|
|
1299
|
-
const changesFollower = new ChangesFollower(client, changesParams);
|
|
1300
|
-
const changesItemsStream = changesFollower.startOneOff();
|
|
1301
|
-
// Create for-async-loop or pipeline to begin the flow of changes
|
|
1302
|
-
// e.g. pipeline(changesItemsStream, destinationStream).then(() => { ... }).catch((err) => { ... });
|
|
1303
|
-
```
|
|
1304
|
-
|
|
1305
|
-
</details>
|
|
1306
|
-
|
|
1307
|
-
##### Processing changes
|
|
1308
|
-
|
|
1309
|
-
###### Process continuous changes
|
|
1310
|
-
<details open>
|
|
1311
|
-
<summary>TypeScript:</summary>
|
|
1312
|
-
|
|
1313
|
-
```ts
|
|
1314
|
-
import { ChangesFollower, CloudantV1, Stream } from '@ibm-cloud/cloudant';
|
|
1315
|
-
import { ChangesResultItem, PostChangesParams } from '@ibm-cloud/cloudant/cloudant/v1';
|
|
1316
|
-
import { Writable } from 'node:stream';
|
|
1317
|
-
import { pipeline } from 'node:stream/promises';
|
|
1318
|
-
```
|
|
1319
|
-
|
|
1320
|
-
```ts
|
|
1321
|
-
const client = CloudantV1.newInstance({});
|
|
1322
|
-
// Start from a previously persisted seq
|
|
1323
|
-
// Normally this would be read by the app from persistent storage
|
|
1324
|
-
// e.g. previouslyPersistedSeq = yourAppPersistenceReadFunc()
|
|
1325
|
-
const previouslyPersistedSeq = '3-g1AG3...';
|
|
1326
|
-
const changesParams: PostChangesParams = {
|
|
1327
|
-
db: 'example',
|
|
1328
|
-
since: previouslyPersistedSeq
|
|
1329
|
-
};
|
|
1330
|
-
const changesFollower = new ChangesFollower(client, changesParams);
|
|
1331
|
-
const changesItemsStream: Stream<ChangesResultItem> = changesFollower.start();
|
|
1332
|
-
|
|
1333
|
-
const destinationStream = new Writable({
|
|
1334
|
-
objectMode: true,
|
|
1335
|
-
write(changesItem: CloudantV1.ChangesResultItem, _, callback) {
|
|
1336
|
-
// do something with change item
|
|
1337
|
-
console.log(changesItem.id);
|
|
1338
|
-
for (const change of changesItem.changes) {
|
|
1339
|
-
console.log(change.rev);
|
|
1340
|
-
}
|
|
1341
|
-
// when change item processing is complete app can store seq
|
|
1342
|
-
const seq = changesItem.seq;
|
|
1343
|
-
// write seq to persistent storage for use as since if required to resume later
|
|
1344
|
-
// e.g. yourAppPersistenceWriteFunc()
|
|
1345
|
-
callback();
|
|
1346
|
-
}
|
|
1347
|
-
});
|
|
1348
|
-
|
|
1349
|
-
// A pipeline to keep processing changes until the follower is stopped or some other stop condition is reached
|
|
1350
|
-
pipeline(changesItemsStream, destinationStream)
|
|
1351
|
-
.then(() => {
|
|
1352
|
-
console.log('Stopped');
|
|
1353
|
-
})
|
|
1354
|
-
.catch((err) => {
|
|
1355
|
-
console.log(err);
|
|
1356
|
-
});
|
|
1357
|
-
```
|
|
1358
|
-
|
|
1359
|
-
</details>
|
|
1360
|
-
|
|
1361
|
-
<details>
|
|
1362
|
-
<summary>JavaScript:</summary>
|
|
1363
|
-
|
|
1364
|
-
```js
|
|
1365
|
-
import { ChangesFollower, CloudantV1 } from '@ibm-cloud/cloudant';
|
|
1366
|
-
import { Writable } from 'node:stream';
|
|
1367
|
-
import { pipeline } from 'node:stream/promises';
|
|
1368
|
-
```
|
|
1369
|
-
|
|
1370
|
-
```js
|
|
1371
|
-
const client = CloudantV1.newInstance();
|
|
1372
|
-
// Start from a previously persisted seq
|
|
1373
|
-
// Normally this would be read by the app from persistent storage
|
|
1374
|
-
// e.g. previouslyPersistedSeq = yourAppPersistenceReadFunc()
|
|
1375
|
-
const previouslyPersistedSeq = '3-g1AG3...';
|
|
1376
|
-
const changesParams = {
|
|
1377
|
-
db: 'example',
|
|
1378
|
-
since: previouslyPersistedSeq
|
|
1379
|
-
};
|
|
1380
|
-
const changesFollower = new ChangesFollower(client, changesParams);
|
|
1381
|
-
const changesItemsStream = changesFollower.start();
|
|
1382
|
-
|
|
1383
|
-
const destinationStream = new Writable({
|
|
1384
|
-
objectMode: true,
|
|
1385
|
-
write(changesItem, _, callback) {
|
|
1386
|
-
// do something with change item
|
|
1387
|
-
console.log(changesItem.id);
|
|
1388
|
-
for (const change of changesItem.changes) {
|
|
1389
|
-
console.log(change.rev);
|
|
1390
|
-
}
|
|
1391
|
-
// when change item processing is complete app can store seq
|
|
1392
|
-
const seq = changesItem.seq;
|
|
1393
|
-
// write seq to persistent storage for use as since if required to resume later
|
|
1394
|
-
// e.g. yourAppPersistenceWriteFunc()
|
|
1395
|
-
callback();
|
|
1396
|
-
}
|
|
1397
|
-
});
|
|
1398
|
-
|
|
1399
|
-
// A pipeline to keep processing changes until the follower is stopped or some other stop condition is reached
|
|
1400
|
-
pipeline(changesItemsStream, destinationStream)
|
|
1401
|
-
.then(() => {
|
|
1402
|
-
console.log('Stopped');
|
|
1403
|
-
})
|
|
1404
|
-
.catch((err) => {
|
|
1405
|
-
console.log(err);
|
|
1406
|
-
});
|
|
1407
|
-
```
|
|
1408
|
-
|
|
1409
|
-
</details>
|
|
1410
|
-
|
|
1411
|
-
###### Process one-off changes
|
|
1412
|
-
<details open>
|
|
1413
|
-
<summary>TypeScript:</summary>
|
|
1414
|
-
|
|
1415
|
-
```ts
|
|
1416
|
-
import { ChangesFollower, CloudantV1, Stream } from '@ibm-cloud/cloudant';
|
|
1417
|
-
import { ChangesResultItem, PostChangesParams } from '@ibm-cloud/cloudant/cloudant/v1';
|
|
1418
|
-
import { Writable } from 'node:stream';
|
|
1419
|
-
import { pipeline } from 'node:stream/promises';
|
|
1420
|
-
```
|
|
1421
|
-
|
|
1422
|
-
```ts
|
|
1423
|
-
const client = CloudantV1.newInstance({});
|
|
1424
|
-
// Start from a previously persisted seq
|
|
1425
|
-
// Normally this would be read by the app from persistent storage
|
|
1426
|
-
// e.g. previouslyPersistedSeq = yourAppPersistenceReadFunc()
|
|
1427
|
-
const previouslyPersistedSeq = '3-g1AG3...';
|
|
1428
|
-
const changesParams: PostChangesParams = {
|
|
1429
|
-
db: 'example',
|
|
1430
|
-
since: previouslyPersistedSeq
|
|
1431
|
-
};
|
|
1432
|
-
const changesFollower: ChangesFollower = new ChangesFollower(client, changesParams);
|
|
1433
|
-
const changesItemsStream: Stream<ChangesResultItem> = changesFollower.startOneOff();
|
|
1434
|
-
|
|
1435
|
-
const destinationStream = new Writable({
|
|
1436
|
-
objectMode: true,
|
|
1437
|
-
write(changesItem: CloudantV1.ChangesResultItem, _, callback) {
|
|
1438
|
-
// do something with change item
|
|
1439
|
-
console.log(changesItem.id);
|
|
1440
|
-
for (const change of changesItem.changes) {
|
|
1441
|
-
console.log(change.rev);
|
|
1442
|
-
}
|
|
1443
|
-
// when change item processing is complete app can store seq
|
|
1444
|
-
const seq = changesItem.seq;
|
|
1445
|
-
// write seq to persistent storage for use as since if required to resume later
|
|
1446
|
-
// e.g. yourAppPersistenceWriteFunc()
|
|
1447
|
-
callback();
|
|
1448
|
-
}
|
|
1449
|
-
});
|
|
1450
|
-
|
|
1451
|
-
pipeline(changesItemsStream, destinationStream)
|
|
1452
|
-
.then(() => {
|
|
1453
|
-
console.log('All changes done');
|
|
1454
|
-
})
|
|
1455
|
-
.catch((err) => {
|
|
1456
|
-
console.log(err);
|
|
1457
|
-
});
|
|
1458
|
-
|
|
1459
|
-
// use for-async-loop feature for stream
|
|
1460
|
-
/*
|
|
1461
|
-
getChangesFromFollower(changesItemsStream);
|
|
1462
|
-
async function getChangesFromFollower(changesItemsStream: Stream<CloudantV1.ChangesResultItem>) {
|
|
1463
|
-
for await (const changesItem of changesItemsStream) {
|
|
1464
|
-
// do something with change item
|
|
1465
|
-
// write seq to persistent storage for use as since
|
|
1466
|
-
console.log(changesItem.id);
|
|
1467
|
-
for (const change of changesItem.changes) {
|
|
1468
|
-
console.log(change.rev);
|
|
1469
|
-
}
|
|
1470
|
-
// when change item processing is complete app can store seq
|
|
1471
|
-
seq = changesItem.seq;
|
|
1472
|
-
// write seq to persistent storage for use as since if required to resume later
|
|
1473
|
-
// e.g. yourAppPersistenceWriteFunc();
|
|
1474
|
-
}
|
|
1475
|
-
}
|
|
1476
|
-
*/
|
|
1477
|
-
```
|
|
1478
|
-
|
|
1479
|
-
</details>
|
|
1480
|
-
|
|
1481
|
-
<details>
|
|
1482
|
-
<summary>JavaScript:</summary>
|
|
1483
|
-
|
|
1484
|
-
```js
|
|
1485
|
-
import { ChangesFollower, CloudantV1 } from '@ibm-cloud/cloudant';
|
|
1486
|
-
import { Writable } from 'node:stream';
|
|
1487
|
-
import { pipeline } from 'node:stream/promises';
|
|
1488
|
-
```
|
|
1489
|
-
|
|
1490
|
-
```js
|
|
1491
|
-
const client = CloudantV1.newInstance();
|
|
1492
|
-
// Start from a previously persisted seq
|
|
1493
|
-
// Normally this would be read by the app from persistent storage
|
|
1494
|
-
// e.g. previouslyPersistedSeq = yourAppPersistenceReadFunc()
|
|
1495
|
-
const previouslyPersistedSeq = '3-g1AG3...';
|
|
1496
|
-
const changesParams = {
|
|
1497
|
-
db: 'example',
|
|
1498
|
-
since: previouslyPersistedSeq
|
|
1499
|
-
};
|
|
1500
|
-
const changesFollower = new ChangesFollower(client, changesParams);
|
|
1501
|
-
const changesItemsStream = changesFollower.startOneOff();
|
|
1502
|
-
|
|
1503
|
-
const destinationStream = new Writable({
|
|
1504
|
-
objectMode: true,
|
|
1505
|
-
write(changesItem, _, callback) {
|
|
1506
|
-
// do something with change item
|
|
1507
|
-
console.log(changesItem.id);
|
|
1508
|
-
for (const change of changesItem.changes) {
|
|
1509
|
-
console.log(change.rev);
|
|
1510
|
-
}
|
|
1511
|
-
// when change item processing is complete app can store seq
|
|
1512
|
-
const seq = changesItem.seq;
|
|
1513
|
-
// write seq to persistent storage for use as since if required to resume later
|
|
1514
|
-
// e.g. yourAppPersistenceWriteFunc()
|
|
1515
|
-
callback();
|
|
1516
|
-
}
|
|
1517
|
-
});
|
|
1518
|
-
|
|
1519
|
-
pipeline(changesItemsStream, destinationStream)
|
|
1520
|
-
.then(() => {
|
|
1521
|
-
console.log('All changes done');
|
|
1522
|
-
})
|
|
1523
|
-
.catch((err) => {
|
|
1524
|
-
console.log(err);
|
|
1525
|
-
});
|
|
1526
|
-
|
|
1527
|
-
// use for-async-loop feature for stream
|
|
1528
|
-
/*
|
|
1529
|
-
getChangesFromFollower(changesItemsStream);
|
|
1530
|
-
async function getChangesFromFollower(changesItemsStream) {
|
|
1531
|
-
for await (const changesItem of changesItemsStream) {
|
|
1532
|
-
// do something with change item
|
|
1533
|
-
// write seq to persistent storage for use as since
|
|
1534
|
-
console.log(changesItem.id);
|
|
1535
|
-
for (const change of changesItem.changes) {
|
|
1536
|
-
console.log(change.rev);
|
|
1537
|
-
}
|
|
1538
|
-
// when change item processing is complete app can store seq
|
|
1539
|
-
seq = changesItem.seq;
|
|
1540
|
-
// write seq to persistent storage for use as since if required to resume later
|
|
1541
|
-
// e.g. yourAppPersistenceWriteFunc();
|
|
1542
|
-
}
|
|
1543
|
-
}
|
|
1544
|
-
*/
|
|
1545
|
-
```
|
|
1546
|
-
|
|
1547
|
-
</details>
|
|
1548
|
-
|
|
1549
|
-
##### Stopping the changes follower
|
|
1550
|
-
<details open>
|
|
1551
|
-
<summary>TypeScript:</summary>
|
|
1552
|
-
|
|
1553
|
-
```ts
|
|
1554
|
-
import { ChangesFollower, CloudantV1, Stream } from '@ibm-cloud/cloudant';
|
|
1555
|
-
import { ChangesResultItem, PostChangesParams } from '@ibm-cloud/cloudant/cloudant/v1';
|
|
1556
|
-
import { Writable } from 'node:stream';
|
|
1557
|
-
import { pipeline } from 'node:stream/promises';
|
|
1558
|
-
```
|
|
1559
|
-
|
|
1560
|
-
```ts
|
|
1561
|
-
const client = CloudantV1.newInstance({});
|
|
1562
|
-
const changesParams: PostChangesParams = {
|
|
1563
|
-
db: 'example'
|
|
1564
|
-
};
|
|
1565
|
-
const changesFollower: ChangesFollower = new ChangesFollower(client, changesParams);
|
|
1566
|
-
const changesItemsStream: Stream<ChangesResultItem> = changesFollower.start();
|
|
1567
|
-
|
|
1568
|
-
const destinationStream = new Writable({
|
|
1569
|
-
objectMode: true,
|
|
1570
|
-
write(changesItem: CloudantV1.ChangesResultItem, _, callback) {
|
|
1571
|
-
// Option 1: call stop after some condition
|
|
1572
|
-
// Note that at least one item
|
|
1573
|
-
// must be returned to reach to this point.
|
|
1574
|
-
// Additional changes may be processed before the iterator stops.
|
|
1575
|
-
changesFollower.stop();
|
|
1576
|
-
callback();
|
|
1577
|
-
}
|
|
1578
|
-
});
|
|
1579
|
-
|
|
1580
|
-
pipeline(changesItemsStream, destinationStream)
|
|
1581
|
-
.then(() => {
|
|
1582
|
-
console.log('Stopped');
|
|
1583
|
-
})
|
|
1584
|
-
.catch((err) => {
|
|
1585
|
-
console.log(err);
|
|
1586
|
-
});
|
|
1587
|
-
|
|
1588
|
-
// Option 2: call stop method when you want to end the continuous loop from
|
|
1589
|
-
// outside the pipeline.
|
|
1590
|
-
// Normally the call would be made from some other application function
|
|
1591
|
-
// executing later.
|
|
1592
|
-
// For example, stop the changesFollower after 1 minute of listening for changes
|
|
1593
|
-
setTimeout(() => {
|
|
1594
|
-
changesFollower.stop();
|
|
1595
|
-
}, 60000);
|
|
1596
|
-
```
|
|
1597
|
-
|
|
1598
|
-
</details>
|
|
1599
|
-
|
|
1600
|
-
<details>
|
|
1601
|
-
<summary>JavaScript:</summary>
|
|
1602
|
-
|
|
1603
|
-
```js
|
|
1604
|
-
import { ChangesFollower, CloudantV1 } from '@ibm-cloud/cloudant';
|
|
1605
|
-
import { Writable } from 'node:stream';
|
|
1606
|
-
import { pipeline } from 'node:stream/promises';
|
|
1607
|
-
```
|
|
1608
|
-
|
|
1609
|
-
```js
|
|
1610
|
-
const client = CloudantV1.newInstance();
|
|
1611
|
-
const changesParams = {
|
|
1612
|
-
db: 'example'
|
|
1613
|
-
};
|
|
1614
|
-
const changesFollower = new ChangesFollower(client, changesParams);
|
|
1615
|
-
const changesItemsStream = changesFollower.start();
|
|
1616
|
-
|
|
1617
|
-
const destinationStream = new Writable({
|
|
1618
|
-
objectMode: true,
|
|
1619
|
-
write(changesItem, _, callback) {
|
|
1620
|
-
// Option 1: call stop after some condition
|
|
1621
|
-
// Note that at least one item
|
|
1622
|
-
// must be returned to reach to this point.
|
|
1623
|
-
// Additional changes may be processed before the iterator stops.
|
|
1624
|
-
changesFollower.stop();
|
|
1625
|
-
callback();
|
|
1626
|
-
}
|
|
1627
|
-
});
|
|
1628
|
-
|
|
1629
|
-
pipeline(changesItemsStream, destinationStream)
|
|
1630
|
-
.then(() =>{
|
|
1631
|
-
console.log('Stopped');
|
|
1632
|
-
})
|
|
1633
|
-
.catch((err) => {
|
|
1634
|
-
console.log(err);
|
|
1635
|
-
});
|
|
1636
|
-
|
|
1637
|
-
// Option 2: call stop method when you want to end the continuous loop from
|
|
1638
|
-
// outside the pipeline.
|
|
1639
|
-
// Normally the call would be made from some other application function
|
|
1640
|
-
// executing later.
|
|
1641
|
-
// For example, stop the changesFollower after 1 minute of listening for changes
|
|
1642
|
-
setTimeout(() => {
|
|
1643
|
-
changesFollower.stop();
|
|
1644
|
-
}, 60000);
|
|
1645
|
-
```
|
|
1646
|
-
|
|
1647
|
-
</details>
|
|
1648
|
-
|
|
1649
|
-
### Pagination (beta)
|
|
1650
|
-
|
|
1651
|
-
#### Introduction
|
|
1652
|
-
|
|
1653
|
-
The pagination feature (currently beta) accepts options for a single operation and automatically
|
|
1654
|
-
creates the multiple requests to the server necessary to page through the results a fixed number at a time.
|
|
1655
|
-
|
|
1656
|
-
Pagination is a best-practice to break apart large queries into multiple server requests.
|
|
1657
|
-
This has a number of advantages:
|
|
1658
|
-
* Keeping requests within server imposed limits, for example
|
|
1659
|
-
* `200` max results for text search
|
|
1660
|
-
* `2000` max results for partitioned queries
|
|
1661
|
-
* Fetching only the necessary data, for example
|
|
1662
|
-
* User finds required result on first page, no need to continue fetching results
|
|
1663
|
-
* Reducing the duration of any individual query
|
|
1664
|
-
* Reduce risk of query timing out on the server
|
|
1665
|
-
* Reduce risk of network request timeouts
|
|
1666
|
-
|
|
1667
|
-
#### Limitations
|
|
1668
|
-
|
|
1669
|
-
Limitations of pagination:
|
|
1670
|
-
* Forward only, no backwards paging
|
|
1671
|
-
* Limitations on `_all_docs` and `_design_docs` operations
|
|
1672
|
-
* No pagination for `key` option.
|
|
1673
|
-
There is no need to paginate as IDs are unique and this returns only a single row.
|
|
1674
|
-
This is better achieved with a single document get request.
|
|
1675
|
-
* No pagination for `keys` option.
|
|
1676
|
-
* Limitations on `_view` operations
|
|
1677
|
-
* No pagination for `key` option. Pass the same `key` as a start and end key instead.
|
|
1678
|
-
* No pagination for `keys` option.
|
|
1679
|
-
* Views that emit multiple identical keys (with the same or different values)
|
|
1680
|
-
from the same document cannot paginate if those key rows with the same ID
|
|
1681
|
-
span a page boundary.
|
|
1682
|
-
The pagination feature detects this condition and an error occurs.
|
|
1683
|
-
It may be possible to workaround using a different page size.
|
|
1684
|
-
* Limitations on `_search` operations
|
|
1685
|
-
* No pagination of grouped results.
|
|
1686
|
-
* No pagination of faceted `counts` or `ranges` results.
|
|
1687
|
-
|
|
1688
|
-
#### Capacity considerations
|
|
1689
|
-
|
|
1690
|
-
Pagination can make many requests rapidly from a single program call.
|
|
1691
|
-
|
|
1692
|
-
For IBM Cloudant take care to ensure you have appropriate plan capacity
|
|
1693
|
-
in place to avoid consuming all the permitted requests.
|
|
1694
|
-
If there is no remaining plan allowance and retries are not enabled or insufficient
|
|
1695
|
-
then a `429 Too Many Requests` error occurs.
|
|
1696
|
-
|
|
1697
|
-
#### Available operations
|
|
1698
|
-
|
|
1699
|
-
Pagination is available for these operations:
|
|
1700
|
-
* Query all documents [global](https://cloud.ibm.com/apidocs/cloudant?code=node#postalldocs)
|
|
1701
|
-
and [partitioned](https://cloud.ibm.com/apidocs/cloudant?code=node#postpartitionalldocs)
|
|
1702
|
-
* [Global all documents examples](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.7/test/examples/src/features/pagination/ts/allDocsPagination.ts)
|
|
1703
|
-
* [Partitioned all documents examples](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.7/test/examples/src/features/pagination/ts/partitionAllDocsPagination.ts)
|
|
1704
|
-
* Query all [design documents](https://cloud.ibm.com/apidocs/cloudant?code=node#postdesigndocs)
|
|
1705
|
-
* [Design documents examples](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.7/test/examples/src/features/pagination/ts/designDocsPagination.ts)
|
|
1706
|
-
* Query with selector syntax [global](https://cloud.ibm.com/apidocs/cloudant?code=node#postfind)
|
|
1707
|
-
and [partitioned](https://cloud.ibm.com/apidocs/cloudant?code=node#postpartitionfind)
|
|
1708
|
-
* [Global find selector query examples](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.7/test/examples/src/features/pagination/ts/findPagination.ts)
|
|
1709
|
-
* [Partitioned find selector query examples](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.7/test/examples/src/features/pagination/ts/partitionFindPagination.ts)
|
|
1710
|
-
* Query a search index [global](https://cloud.ibm.com/apidocs/cloudant?code=node#postsearch)
|
|
1711
|
-
and [partitioned](https://cloud.ibm.com/apidocs/cloudant?code=node#postpartitionsearch)
|
|
1712
|
-
* [Global search examples](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.7/test/examples/src/features/pagination/ts/searchPagination.ts)
|
|
1713
|
-
* [Partitioned search examples](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.7/test/examples/src/features/pagination/ts/partitionSearchPagination.ts)
|
|
1714
|
-
* Query a MapReduce view [global](https://cloud.ibm.com/apidocs/cloudant?code=node#postview)
|
|
1715
|
-
and [partitioned](https://cloud.ibm.com/apidocs/cloudant?code=node#postpartitionview)
|
|
1716
|
-
* [Global view examples](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.7/test/examples/src/features/pagination/ts/viewPagination.ts)
|
|
1717
|
-
* [Partitioned view examples](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.7/test/examples/src/features/pagination/ts/partitionViewPagination.ts)
|
|
1718
|
-
|
|
1719
|
-
The examples presented in this `README` are for all documents in a partition.
|
|
1720
|
-
The links in the list are to equivalent examples for each of the other available operations.
|
|
1721
|
-
|
|
1722
|
-
#### Creating a pagination
|
|
1723
|
-
|
|
1724
|
-
Make a new pagination from a client
|
|
1725
|
-
and the options for the chosen operation.
|
|
1726
|
-
Use the `limit` option to configure the page size (default and maximum `200`).
|
|
1727
|
-
|
|
1728
|
-
Imports required for these examples:
|
|
1729
|
-
|
|
1730
|
-
<details open>
|
|
1731
|
-
<summary>TypeScript:</summary>
|
|
1732
|
-
|
|
1733
|
-
```ts
|
|
1734
|
-
import {
|
|
1735
|
-
CloudantV1,
|
|
1736
|
-
PagerType,
|
|
1737
|
-
Pagination,
|
|
1738
|
-
Pager,
|
|
1739
|
-
Stream,
|
|
1740
|
-
} from '@ibm-cloud/cloudant';
|
|
1741
|
-
import { Writable } from 'node:stream';
|
|
1742
|
-
import { pipeline } from 'node:stream/promises';
|
|
1743
|
-
```
|
|
1744
|
-
|
|
1745
|
-
</details>
|
|
1746
|
-
|
|
1747
|
-
<details>
|
|
1748
|
-
<summary>JavaScript:</summary>
|
|
1749
|
-
|
|
1750
|
-
```js
|
|
1751
|
-
import { CloudantV1, Pagination, PagerType } from '@ibm-cloud/cloudant';
|
|
1752
|
-
import { Writable } from 'node:stream';
|
|
1753
|
-
import { pipeline } from 'node:stream/promises';
|
|
1754
|
-
```
|
|
1755
|
-
|
|
1756
|
-
</details>
|
|
1757
|
-
|
|
1758
|
-
##### Initialize the service
|
|
1759
|
-
|
|
1760
|
-
<details open>
|
|
1761
|
-
<summary>TypeScript:</summary>
|
|
1762
|
-
|
|
1763
|
-
```ts
|
|
1764
|
-
// Initialize service
|
|
1765
|
-
const client: CloudantV1 = CloudantV1.newInstance({});
|
|
1766
|
-
```
|
|
1767
|
-
|
|
1768
|
-
</details>
|
|
1769
|
-
|
|
1770
|
-
<details>
|
|
1771
|
-
<summary>JavaScript:</summary>
|
|
1772
|
-
|
|
1773
|
-
```js
|
|
1774
|
-
// Initialize service
|
|
1775
|
-
const client = CloudantV1.newInstance();
|
|
1776
|
-
```
|
|
1777
|
-
|
|
1778
|
-
</details>
|
|
1779
|
-
|
|
1780
|
-
##### Set the options
|
|
1781
|
-
|
|
1782
|
-
<details open>
|
|
1783
|
-
<summary>TypeScript:</summary>
|
|
1784
|
-
|
|
1785
|
-
```ts
|
|
1786
|
-
// Setup params
|
|
1787
|
-
const paginationParams: CloudantV1.PostPartitionAllDocsParams = {
|
|
1788
|
-
db: 'events', // Required: the database name.
|
|
1789
|
-
limit: 50, // Optional: limit parameter sets the page size. Default and max is 200.
|
|
1790
|
-
partitionKey: 'ns1HJS13AMkK', // query only this partition
|
|
1791
|
-
};
|
|
1792
|
-
```
|
|
1793
|
-
|
|
1794
|
-
</details>
|
|
1795
|
-
|
|
1796
|
-
<details>
|
|
1797
|
-
<summary>JavaScript:</summary>
|
|
1798
|
-
|
|
1799
|
-
```js
|
|
1800
|
-
// Setup params
|
|
1801
|
-
const paginationParams = {
|
|
1802
|
-
db: 'events', // Required: the database name.
|
|
1803
|
-
limit: 50, // Optional: limit parameter sets the page size. Default and max is 200.
|
|
1804
|
-
partitionKey: 'ns1HJS13AMkK', // query only this partition
|
|
1805
|
-
};
|
|
1806
|
-
```
|
|
1807
|
-
|
|
1808
|
-
</details>
|
|
1809
|
-
|
|
1810
|
-
##### Create the pagination
|
|
1811
|
-
|
|
1812
|
-
<details open>
|
|
1813
|
-
<summary>TypeScript:</summary>
|
|
1814
|
-
|
|
1815
|
-
```ts
|
|
1816
|
-
// Create pagination
|
|
1817
|
-
// pagination can be reused without side-effects as a factory for async iterables, streams or pagers
|
|
1818
|
-
const pagination: Pagination<CloudantV1.DocsResultRow> =
|
|
1819
|
-
Pagination.newPagination(
|
|
1820
|
-
client, // Required: the Cloudant service client instance.
|
|
1821
|
-
PagerType.POST_PARTITION_ALL_DOCS, // Required: Pager type
|
|
1822
|
-
paginationParams // Required: pagination configuration params are fixed at pagination creation time
|
|
1823
|
-
);
|
|
1824
|
-
```
|
|
1825
|
-
|
|
1826
|
-
</details>
|
|
1827
|
-
|
|
1828
|
-
<details>
|
|
1829
|
-
<summary>JavaScript:</summary>
|
|
1830
|
-
|
|
1831
|
-
```js
|
|
1832
|
-
// Create pagination
|
|
1833
|
-
// pagination can be reused without side-effects as a factory for async iterables, streams or pagers
|
|
1834
|
-
const pagination = Pagination.newPagination(
|
|
1835
|
-
client, // Required: the Cloudant service client instance.
|
|
1836
|
-
PagerType.POST_PARTITION_ALL_DOCS, // Required: Pager type
|
|
1837
|
-
paginationParams // Required: pagination configuration params are fixed at pagination creation time
|
|
1838
|
-
);
|
|
1839
|
-
```
|
|
1840
|
-
|
|
1841
|
-
</details>
|
|
1842
|
-
|
|
1843
|
-
#### Using pagination
|
|
1844
|
-
|
|
1845
|
-
Once you have a pagination factory there are multiple options available.
|
|
1846
|
-
* Stream pages
|
|
1847
|
-
* Stream rows
|
|
1848
|
-
* Iterate pages
|
|
1849
|
-
* Iterate rows
|
|
1850
|
-
* Get each page from a pager
|
|
1851
|
-
* Get all results from a pager
|
|
1852
|
-
|
|
1853
|
-
All the paging styles produce equivalent results and make identical page requests.
|
|
1854
|
-
The style of paging to choose depends on the use case requirements
|
|
1855
|
-
in particular whether to process a page at a time or a row at a time.
|
|
1856
|
-
|
|
1857
|
-
The pagination factory is reusable and can repeatedly produce new instances
|
|
1858
|
-
of the same or different pagination styles for the same operation options.
|
|
1859
|
-
|
|
1860
|
-
Here are examples for each paging style.
|
|
1861
|
-
|
|
1862
|
-
##### Stream pages
|
|
1863
|
-
|
|
1864
|
-
Streaming pages is ideal for lazy processing of pages
|
|
1865
|
-
and leveraging Node.js's built-in stream utilities.
|
|
1866
|
-
|
|
1867
|
-
<details open>
|
|
1868
|
-
<summary>TypeScript:</summary>
|
|
1869
|
-
|
|
1870
|
-
```ts
|
|
1871
|
-
// Option: stream pages
|
|
1872
|
-
const pageStream: Stream<ReadonlyArray<CloudantV1.DocsResultRow>> =
|
|
1873
|
-
pagination.pageStream(); // a new stream of the pages
|
|
1874
|
-
const destinationPageStream = new Writable({
|
|
1875
|
-
objectMode: true,
|
|
1876
|
-
write(page: Array<CloudantV1.DocsResultRow>, _, callback) {
|
|
1877
|
-
// Do something with page
|
|
1878
|
-
callback();
|
|
1879
|
-
},
|
|
1880
|
-
});
|
|
1881
|
-
(async () => {
|
|
1882
|
-
await pipeline(pageStream, destinationPageStream)
|
|
1883
|
-
.then(() => {
|
|
1884
|
-
console.log('Page stream is done');
|
|
1885
|
-
})
|
|
1886
|
-
.catch((err) => {
|
|
1887
|
-
console.log(err);
|
|
1888
|
-
});
|
|
1889
|
-
})();
|
|
1890
|
-
```
|
|
1891
|
-
|
|
1892
|
-
</details>
|
|
1893
|
-
|
|
1894
|
-
<details>
|
|
1895
|
-
<summary>JavaScript:</summary>
|
|
1896
|
-
|
|
1897
|
-
```js
|
|
1898
|
-
// Option: stream pages
|
|
1899
|
-
const pageStream = pagination.pageStream(); // a new stream of the pages
|
|
1900
|
-
const destinationPageStream = new Writable({
|
|
1901
|
-
objectMode: true,
|
|
1902
|
-
write(page, _, callback) {
|
|
1903
|
-
// Do something with page
|
|
1904
|
-
callback();
|
|
1905
|
-
},
|
|
1906
|
-
});
|
|
1907
|
-
(async () => {
|
|
1908
|
-
await pipeline(pageStream, destinationPageStream)
|
|
1909
|
-
.then(() => {
|
|
1910
|
-
console.log('Page stream is done');
|
|
1911
|
-
})
|
|
1912
|
-
.catch((err) => {
|
|
1913
|
-
console.log(err);
|
|
1914
|
-
});
|
|
1915
|
-
})();
|
|
1916
|
-
```
|
|
1917
|
-
|
|
1918
|
-
</details>
|
|
1919
|
-
|
|
1920
|
-
##### Stream rows
|
|
1921
|
-
|
|
1922
|
-
Streaming pages is ideal for lazy processing of rows
|
|
1923
|
-
and leveraging Node.js's built-in stream utilities.
|
|
1924
|
-
|
|
1925
|
-
<details open>
|
|
1926
|
-
<summary>TypeScript:</summary>
|
|
1927
|
-
|
|
1928
|
-
```ts
|
|
1929
|
-
// Option: stream rows
|
|
1930
|
-
const rowStream: Stream<CloudantV1.DocsResultRow> = pagination.rowStream(); // a new stream of the rows
|
|
1931
|
-
const destinationRowStream = new Writable({
|
|
1932
|
-
objectMode: true,
|
|
1933
|
-
write(row: CloudantV1.DocsResultRow, _, callback) {
|
|
1934
|
-
// Do something with row
|
|
1935
|
-
callback();
|
|
1936
|
-
},
|
|
1937
|
-
});
|
|
1938
|
-
(async () => {
|
|
1939
|
-
await pipeline(rowStream, destinationRowStream)
|
|
1940
|
-
.then(() => {
|
|
1941
|
-
console.log('Row stream is done');
|
|
1942
|
-
})
|
|
1943
|
-
.catch((err) => {
|
|
1944
|
-
console.log(err);
|
|
1945
|
-
});
|
|
1946
|
-
})();
|
|
1947
|
-
```
|
|
1948
|
-
|
|
1949
|
-
</details>
|
|
1950
|
-
|
|
1951
|
-
<details>
|
|
1952
|
-
<summary>JavaScript:</summary>
|
|
1953
|
-
|
|
1954
|
-
```js
|
|
1955
|
-
// Option: stream rows
|
|
1956
|
-
const rowStream = pagination.rowStream(); // a new stream of the rows
|
|
1957
|
-
const destinationRowStream = new Writable({
|
|
1958
|
-
objectMode: true,
|
|
1959
|
-
write(row, _, callback) {
|
|
1960
|
-
// Do something with row
|
|
1961
|
-
callback();
|
|
1962
|
-
},
|
|
1963
|
-
});
|
|
1964
|
-
(async () => {
|
|
1965
|
-
await pipeline(rowStream, destinationRowStream)
|
|
1966
|
-
.then(() => {
|
|
1967
|
-
console.log('Row stream is done');
|
|
1968
|
-
})
|
|
1969
|
-
.catch((err) => {
|
|
1970
|
-
console.log(err);
|
|
1971
|
-
});
|
|
1972
|
-
})();
|
|
1973
|
-
```
|
|
1974
|
-
|
|
1975
|
-
</details>
|
|
1976
|
-
|
|
1977
|
-
##### Iterate pages
|
|
1978
|
-
|
|
1979
|
-
Iterating pages is ideal for using a for await...of statement to process a page at a time.
|
|
1980
|
-
|
|
1981
|
-
<details open>
|
|
1982
|
-
<summary>TypeScript:</summary>
|
|
1983
|
-
|
|
1984
|
-
```ts
|
|
1985
|
-
// Option: iterate pages with for await...of statement
|
|
1986
|
-
(async () => {
|
|
1987
|
-
for await (const page of pagination.pages()) {
|
|
1988
|
-
// Do something with page
|
|
1989
|
-
}
|
|
1990
|
-
})();
|
|
1991
|
-
// Note: Alternatively to for await....of the iterator protocol functions and properties, like
|
|
1992
|
-
// `next()`, `done`, value`, can be used on the iterator returned from pages().
|
|
1993
|
-
// As `next()` returns with a Promise, use `await` or `.then()` on it.
|
|
1994
|
-
```
|
|
1995
|
-
|
|
1996
|
-
</details>
|
|
1997
|
-
|
|
1998
|
-
<details>
|
|
1999
|
-
<summary>JavaScript:</summary>
|
|
2000
|
-
|
|
2001
|
-
```js
|
|
2002
|
-
// Option: iterate pages with for await...of statement
|
|
2003
|
-
(async () => {
|
|
2004
|
-
for await (const page of pagination.pages()) {
|
|
2005
|
-
// Do something with page
|
|
2006
|
-
}
|
|
2007
|
-
})();
|
|
2008
|
-
// Note: Alternatively to for await....of the iterator protocol functions and properties, like
|
|
2009
|
-
// `next()`, `done`, value`, can be used on the iterator returned from pages().
|
|
2010
|
-
// As `next()` returns with a Promise, use `await` or `.then()` on it.
|
|
2011
|
-
```
|
|
2012
|
-
|
|
2013
|
-
</details>
|
|
2014
|
-
|
|
2015
|
-
##### Iterate rows
|
|
2016
|
-
|
|
2017
|
-
Iterating rows is ideal for using a for await...of statement to process a result row at a time.
|
|
2018
|
-
|
|
2019
|
-
<details open>
|
|
2020
|
-
<summary>TypeScript:</summary>
|
|
2021
|
-
|
|
2022
|
-
```ts
|
|
2023
|
-
// Option: iterate rows with for await...of statement
|
|
2024
|
-
(async () => {
|
|
2025
|
-
for await (const row of pagination.rows()) {
|
|
2026
|
-
// Do something with row
|
|
2027
|
-
}
|
|
2028
|
-
})();
|
|
2029
|
-
// Note: Alternatively to for await....of the iterator protocol functions and properties:
|
|
2030
|
-
// `next()`, `done`, value`, can be also used on rows().
|
|
2031
|
-
// As `next(`)` returns with a Promise, make sure using `await` or `.then()` on it.
|
|
2032
|
-
```
|
|
2033
|
-
|
|
2034
|
-
</details>
|
|
2035
|
-
|
|
2036
|
-
<details>
|
|
2037
|
-
<summary>JavaScript:</summary>
|
|
2038
|
-
|
|
2039
|
-
```js
|
|
2040
|
-
// Option: iterate rows with for await...of statement
|
|
2041
|
-
(async () => {
|
|
2042
|
-
for await (const row of pagination.rows()) {
|
|
2043
|
-
// Do something with row
|
|
2044
|
-
}
|
|
2045
|
-
})();
|
|
2046
|
-
// Note: Alternatively to for await....of the iterator protocol functions and properties:
|
|
2047
|
-
// `next()`, `done`, value`, can be also used on rows().
|
|
2048
|
-
// As `next(`)` returns with a Promise, make sure using `await` or `.then()` on it.
|
|
2049
|
-
```
|
|
2050
|
-
|
|
2051
|
-
</details>
|
|
2052
|
-
|
|
2053
|
-
##### Pager
|
|
2054
|
-
|
|
2055
|
-
The pager style is similar to other [IBM Cloud SDKs](https://github.com/IBM/ibm-cloud-sdk-common?tab=readme-ov-file#pagination).
|
|
2056
|
-
Users familiar with that style of pagination may find using them preferable
|
|
2057
|
-
to the native language style iterators.
|
|
2058
|
-
|
|
2059
|
-
In the Cloudant SDKs these pagers are single use and traverse the complete set of pages once and only once.
|
|
2060
|
-
After exhaustion they cannot be re-used, simply create a new one from the pagination factory if needed.
|
|
2061
|
-
|
|
2062
|
-
Pagers are only valid for one of either page at a time or getting all results.
|
|
2063
|
-
For example, calling for the next page then calling for all results causes an error.
|
|
2064
|
-
|
|
2065
|
-
###### Get each page from a pager
|
|
2066
|
-
|
|
2067
|
-
This is useful for calling to retrieve one page at a time, for example,
|
|
2068
|
-
in a user interface with a "next page" interaction.
|
|
2069
|
-
|
|
2070
|
-
If calling for the next page errors, it is valid to call for the next page again
|
|
2071
|
-
to continue paging.
|
|
2072
|
-
|
|
2073
|
-
<details open>
|
|
2074
|
-
<summary>TypeScript:</summary>
|
|
2075
|
-
|
|
2076
|
-
```ts
|
|
2077
|
-
// Option: use pager next page
|
|
2078
|
-
// For retrieving one page at a time with a function call.
|
|
2079
|
-
const pager: Pager<CloudantV1.DocsResultRow> = pagination.pager();
|
|
2080
|
-
(async () => {
|
|
2081
|
-
if (pager.hasNext()) {
|
|
2082
|
-
const page: Array<CloudantV1.DocsResultRow> = await pager.getNext();
|
|
2083
|
-
// Do something with page
|
|
2084
|
-
}
|
|
2085
|
-
})();
|
|
2086
|
-
```
|
|
2087
|
-
|
|
2088
|
-
</details>
|
|
2089
|
-
|
|
2090
|
-
<details>
|
|
2091
|
-
<summary>JavaScript:</summary>
|
|
2092
|
-
|
|
2093
|
-
```js
|
|
2094
|
-
// Option: use pager next page
|
|
2095
|
-
// For retrieving one page at a time with a function call.
|
|
2096
|
-
const pager = pagination.pager();
|
|
2097
|
-
(async () => {
|
|
2098
|
-
if (pager.hasNext()) {
|
|
2099
|
-
const page = await pager.getNext();
|
|
2100
|
-
// Do something with page
|
|
2101
|
-
}
|
|
2102
|
-
})();
|
|
2103
|
-
```
|
|
2104
|
-
|
|
2105
|
-
</details>
|
|
2106
|
-
|
|
2107
|
-
###### Get all results from a pager
|
|
2108
|
-
|
|
2109
|
-
This is useful to retrieve all results in a single call.
|
|
2110
|
-
However, this approach requires sufficient memory for the entire collection of results.
|
|
2111
|
-
So although it may be convenient for small result sets generally prefer iterating pages
|
|
2112
|
-
or rows with the other paging styles, especially for large result sets.
|
|
2113
|
-
|
|
2114
|
-
If calling for all the results errors, then calling for all the results again restarts the pagination.
|
|
2115
|
-
|
|
2116
|
-
<details open>
|
|
2117
|
-
<summary>TypeScript:</summary>
|
|
2118
|
-
|
|
2119
|
-
```ts
|
|
2120
|
-
// Option: use pager all results
|
|
2121
|
-
// For retrieving all result rows in a single list
|
|
2122
|
-
// Note: all result rows may be very large!
|
|
2123
|
-
// Preferably use streams/iterables instead of getAll for memory efficiency with large result sets.
|
|
2124
|
-
const allPager: Pager<CloudantV1.DocsResultRow> = pagination.pager();
|
|
2125
|
-
(async () => {
|
|
2126
|
-
const allRows: Array<CloudantV1.DocsResultRow> = await allPager.getAll();
|
|
2127
|
-
for (const row of allRows) {
|
|
2128
|
-
// Do something with row
|
|
2129
|
-
}
|
|
2130
|
-
})();
|
|
2131
|
-
```
|
|
2132
|
-
|
|
2133
|
-
</details>
|
|
2134
|
-
|
|
2135
|
-
<details>
|
|
2136
|
-
<summary>JavaScript:</summary>
|
|
2137
|
-
|
|
2138
|
-
```js
|
|
2139
|
-
// Option: use pager all results
|
|
2140
|
-
// For retrieving all result rows in a single list
|
|
2141
|
-
// Note: all result rows may be very large!
|
|
2142
|
-
// Preferably use streams/iterables instead of getAll for memory efficiency with large result sets.
|
|
2143
|
-
const allPager = pagination.pager();
|
|
2144
|
-
(async () => {
|
|
2145
|
-
const allRows = await allPager.getAll();
|
|
2146
|
-
for (const row of allRows) {
|
|
2147
|
-
// Do something with row
|
|
2148
|
-
}
|
|
2149
|
-
})();
|
|
2150
|
-
```
|
|
2151
|
-
|
|
2152
|
-
</details>
|
|
2153
|
-
|
|
2154
272
|
## Questions
|
|
2155
273
|
|
|
2156
274
|
If you are having difficulties using this SDK or have a question about the
|
|
@@ -2164,7 +282,7 @@ If you encounter an issue with the project, you are welcome to submit a
|
|
|
2164
282
|
|
|
2165
283
|
Before you submit a bug report, search for
|
|
2166
284
|
[similar issues](https://github.com/IBM/cloudant-node-sdk/issues?q=is%3Aissue) and review the
|
|
2167
|
-
[KNOWN_ISSUES file](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.
|
|
285
|
+
[KNOWN_ISSUES file](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.9/KNOWN_ISSUES.md) to verify that your issue hasn't been reported yet.
|
|
2168
286
|
|
|
2169
287
|
Please consult the [security policy](https://github.com/IBM/cloudant-node-sdk/security/policy) before opening security related issues.
|
|
2170
288
|
|
|
@@ -2194,8 +312,8 @@ Find more open source projects on the [IBM GitHub](http://ibm.github.io/) page.
|
|
|
2194
312
|
|
|
2195
313
|
## Contributing
|
|
2196
314
|
|
|
2197
|
-
For more information, see [CONTRIBUTING](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.
|
|
315
|
+
For more information, see [CONTRIBUTING](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.9/CONTRIBUTING.md).
|
|
2198
316
|
|
|
2199
317
|
## License
|
|
2200
318
|
|
|
2201
|
-
This SDK is released under the Apache 2.0 license. To read the full text of the license, see [LICENSE](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.
|
|
319
|
+
This SDK is released under the Apache 2.0 license. To read the full text of the license, see [LICENSE](https://github.com/IBM/cloudant-node-sdk/tree/v0.12.9/LICENSE).
|