@ibm-cloud/cloudant 0.0.10 → 0.0.14

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 CHANGED
@@ -1,25 +1,25 @@
1
1
  <!--
2
- The example codes and outputs below are generated using the `embedmd` go package.
2
+ The example codes and outputs below are generated using the `embedmd` go
3
+ package.
3
4
 
4
5
  https://github.com/campoy/embedmd
5
6
 
6
- You should regenerate the example codes after making any changes to examples in the test/examples/ folder.
7
+ You should regenerate the example codes after making any changes to
8
+ examples in the test/examples/ folder.
7
9
 
8
10
  embedmd -w README.md
9
11
  -->
10
12
 
11
13
  [![Build Status](https://travis-ci.com/IBM/cloudant-node-sdk.svg?branch=master)](https://travis-ci.com/IBM/cloudant-node-sdk)
12
- <!--
13
- [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
14
- [![npm-version](https://img.shields.io/npm/v/IBM/cloudant-node-sdk.svg)](https://www.npmjs.com/package/@ibmcloud/cloudant)
15
- [![codecov](https://codecov.io/gh/IBM/cloudant-node-sdk/branch/master/graph/badge.svg)](https://codecov.io/gh/IBM/cloudant-node-sdk)
16
- -->
14
+ [![Release](https://img.shields.io/github/v/release/IBM/cloudant-node-sdk?include_prereleases&sort=semver)](https://github.com/IBM/cloudant-node-sdk/releases/latest)
15
+ [![Docs](https://img.shields.io/static/v1?label=nodedoc&message=latest&color=blue)](https://ibm.github.io/cloudant-node-sdk/)
17
16
 
18
- # IBM Cloudant Node.js SDK Version 0.0.10
17
+ # IBM Cloudant Node.js SDK Version 0.0.14
19
18
 
20
- Node.js client library to interact with various [Cloudant APIs](https://cloud.ibm.com/apidocs/cloudant?code=node).
19
+ IBM Cloudant Node.js SDK is a client library that interacts with the
20
+ [IBM Cloudant APIs](https://cloud.ibm.com/apidocs/cloudant?code=node).
21
21
 
22
- Disclaimer: this SDK is being released initially as a **pre-release** version.
22
+ Disclaimer: This SDK is being released initially as a **pre-release** version.
23
23
  Changes might occur which impact applications that use this SDK.
24
24
 
25
25
  <details>
@@ -30,8 +30,6 @@ Changes might occur which impact applications that use this SDK.
30
30
 
31
31
  https://github.com/jonschlinkert/markdown-toc
32
32
 
33
- You should regenerate the TOC after making changes to this file.
34
-
35
33
  npx markdown-toc -i README.md
36
34
  -->
37
35
 
@@ -41,21 +39,25 @@ Changes might occur which impact applications that use this SDK.
41
39
  - [Features](#features)
42
40
  - [Prerequisites](#prerequisites)
43
41
  - [Installation](#installation)
44
- - [Getting started](#getting-started)
45
- * [Authentication](#authentication)
42
+ - [Authentication](#authentication)
43
+ * [Authentication with environment variables](#authentication-with-environment-variables)
46
44
  + [IAM authentication](#iam-authentication)
47
45
  + [Session cookie authentication](#session-cookie-authentication)
48
46
  + [Basic authentication](#basic-authentication)
47
+ * [Authentication with external configuration](#authentication-with-external-configuration)
48
+ * [Programmatic authentication](#programmatic-authentication)
49
+ - [Using the SDK](#using-the-sdk)
49
50
  * [Code examples](#code-examples)
50
51
  + [1. Retrieve information from an existing database](#1-retrieve-information-from-an-existing-database)
51
52
  + [2. Create your own database and add a document](#2-create-your-own-database-and-add-a-document)
52
53
  + [3. Update your previously created document](#3-update-your-previously-created-document)
53
54
  + [4. Delete your previously created document](#4-delete-your-previously-created-document)
54
- - [Using the SDK](#using-the-sdk)
55
+ * [Error handling](#error-handling)
56
+ * [Raw IO](#raw-io)
57
+ * [Further resources](#further-resources)
55
58
  - [Questions](#questions)
56
59
  - [Issues](#issues)
57
- - [Further resources](#further-resources)
58
- - [Open source @ IBM](#open-source--ibm)
60
+ - [Open source at IBM](#open-source-at-ibm)
59
61
  - [Contributing](#contributing)
60
62
  - [License](#license)
61
63
 
@@ -65,29 +67,42 @@ Changes might occur which impact applications that use this SDK.
65
67
 
66
68
  ## Overview
67
69
 
68
- The IBM Cloudant Node.js SDK allows developers to programmatically interact with [Cloudant](https://cloud.ibm.com/apidocs/cloudant?code=node).
70
+ The IBM Cloudant Node.js SDK allows developers to programmatically
71
+ interact with [IBM Cloudant](https://cloud.ibm.com/apidocs/cloudant)
72
+ with the help of the `@ibm-cloud/cloudant` package.
69
73
 
70
74
  ## Features
71
75
 
72
- The purpose of this Node.js SDK is to wrap most of the HTTP request APIs provided by Cloudant and
73
- supply other functions to ease the usage of Cloudant.
74
- This SDK should make life easier for programmers to do what’s really important for them: develop.
76
+ The purpose of this Node.js SDK is to wrap most of the HTTP request APIs
77
+ provided by Cloudant and supply other functions to ease the usage of Cloudant.
78
+ This SDK should make life easier for programmers to do what’s really important
79
+ to them: developing software.
75
80
 
76
- Reasons why you should consider using Cloudant SDK for Node.js in your project:
81
+ Reasons why you should consider using Cloudant Node.js SDK in your
82
+ project:
77
83
 
78
84
  - Supported by IBM Cloudant.
79
- - Includes all the most popular and latest supported endpoints for applications.
85
+ - Server compatibility with:
86
+ - IBM Cloudant "Classic".
87
+ - [Cloudant "Standard on Transaction Engine"](https://cloud.ibm.com/docs/Cloudant?topic=Cloudant-overview-te) for APIs compatible with Cloudant "Classic". For more information, see the [Feature Parity](https://cloud.ibm.com/docs/Cloudant?topic=Cloudant-overview-te#feature-parity-between-ibm-cloudant-on-the-transaction-engine-vs-classic-architecture) page.
88
+ - [Apache CouchDB 3.x](https://docs.couchdb.org/en/stable/) for data operations.
89
+ - Includes all the most popular and latest supported endpoints for
90
+ applications.
80
91
  - Handles the authentication.
81
- - Familiar user experience of IBM Cloud SDKs.
92
+ - Familiar user experience with IBM Cloud SDKs.
93
+ - Flexibility to use either built-in models or byte-based requests and responses for documents.
82
94
  - `Promise` based design with asynchronous HTTP requests.
83
95
  - Use either as native JavaScript or take advantage of TypeScript models.
96
+ - Transparently compresses request and response bodies.
84
97
 
85
98
  ## Prerequisites
86
99
 
87
- - You need an [IBM Cloud][ibm-cloud-onboarding] account.
88
- - **Node.js 10, 12, 14**: This SDK is tested with Node.js versions 10, 12, and 14. It may work on other versions but those are not officially supported.
89
-
90
- [ibm-cloud-onboarding]: http://cloud.ibm.com/registration
100
+ - A
101
+ [Cloudant](https://cloud.ibm.com/docs/Cloudant/getting-started.html#step-1-connect-to-your-cloudant-nosql-db-service-instance-on-ibm-cloud)
102
+ service instance or a
103
+ [CouchDB](https://docs.couchdb.org/en/latest/install/index.html)
104
+ server.
105
+ - Node.js 10, 12 or 14.
91
106
 
92
107
  ## Installation
93
108
 
@@ -95,39 +110,66 @@ Reasons why you should consider using Cloudant SDK for Node.js in your project:
95
110
  npm install @ibm-cloud/cloudant
96
111
  ```
97
112
 
98
- ## Getting started
113
+ ## Authentication
99
114
 
100
- ### Authentication
115
+ [service-credentials]: https://cloud.ibm.com/docs/Cloudant?topic=cloudant-creating-an-ibm-cloudant-instance-on-ibm-cloud#locating-your-service-credentials
116
+ [cloud-IAM-mgmt]: https://cloud.ibm.com/docs/Cloudant?topic=cloudant-ibm-cloud-identity-and-access-management-iam-
117
+ [couch-cookie-auth]: https://docs.couchdb.org/en/stable/api/server/authn.html#cookie-authentication
118
+ [cloudant-cookie-auth]: https://cloud.ibm.com/docs/Cloudant?topic=cloudant-authentication#cookie-authentication
119
+ [couch-basic-auth]: https://docs.couchdb.org/en/stable/api/server/authn.html#basic-authentication
120
+ [cloudant-basic-auth]: https://cloud.ibm.com/docs/services/Cloudant/api?topic=cloudant-authentication#basic-authentication
101
121
 
102
- This library requires some of your [Cloudant service credentials](https://cloud.ibm.com/docs/Cloudant?topic=cloudant-creating-an-ibm-cloudant-instance-on-ibm-cloud#locating-your-service-credentials) to authenticate with your account.
122
+ This library requires some of your
123
+ [Cloudant service credentials][service-credentials] to authenticate with your
124
+ account.
103
125
 
104
126
  1. `IAM`, `COUCHDB_SESSION`, `BASIC` or `NOAUTH` **authentication type**.
105
- 1. [*IAM authentication*](#iam-authentication) is highly recommended when your back-end database server is [**Cloudant**](https://cloud.ibm.com/docs/Cloudant?topic=cloudant-ibm-cloud-identity-and-access-management-iam-). This authentication type requires a server-generated `apikey` instead of a user-given password.
106
- 1. [*Session cookie (`COUCHDB_SESSION`) authentication*](#session-cookie-authentication) is recommended for [Apache CouchDB](https://docs.couchdb.org/en/stable/api/server/authn.html#cookie-authentication) or for [Cloudant](https://cloud.ibm.com/docs/Cloudant?topic=cloudant-authentication#cookie-authentication) when IAM is unavailable. It exchanges username and password credentials for an `AuthSession` cookie from the `/_session` endpoint.
107
- 1. [*Basic* (or legacy) *authentication*](#basic-authentication) is good for both [Cloudant](https://cloud.ibm.com/docs/services/Cloudant/api?topic=cloudant-authentication#basic-authentication) and [CouchDB](https://docs.couchdb.org/en/stable/api/server/authn.html#basic-authentication) back-end database servers. This authentication type requires the good old `username` and `password` credentials.
108
- 1. *Noauth* authentication does not need any credentials. Note that this authentication type will only work for queries against a database with read access for everyone.
109
- 1. The service `url`
110
-
111
- You have to add these properties as your **environment variables**, because some
112
- examples that follow assume that these variables are set.
113
- To learn more about authentication configuration see the related documentation in the
114
- [Cloudant API docs](https://cloud.ibm.com/apidocs/cloudant#authentication?code=node) or in the
115
- [general SDK usage information](https://github.com/IBM/ibm-cloud-sdk-common#authentication).
127
+ 1. [*IAM authentication*](#iam-authentication) is highly recommended when your
128
+ back-end database server is [**Cloudant**][cloud-IAM-mgmt]. This
129
+ authentication type requires a server-generated `apikey` instead of a
130
+ user-given password. You can create one
131
+ [here](https://cloud.ibm.com/iam/apikeys).
132
+ 1. [*Session cookie (`COUCHDB_SESSION`) authentication*](#session-cookie-authentication)
133
+ is recommended for [Apache CouchDB][couch-cookie-auth] or for
134
+ [Cloudant][cloudant-cookie-auth] when IAM is unavailable. It exchanges username
135
+ and password credentials for an `AuthSession` cookie from the `/_session`
136
+ endpoint.
137
+ 1. [*Basic* (or legacy) *authentication*](#basic-authentication) is a fallback
138
+ for both [Cloudant][cloudant-basic-auth] and [Apache CouchDB][couch-basic-auth]
139
+ back-end database servers. This authentication type requires the good old
140
+ `username` and `password` credentials.
141
+ 1. *Noauth* authentication does not require credentials. Note that this
142
+ authentication type only works with queries against a database with read
143
+ access for everyone.
144
+ 1. The service `url`.
145
+
146
+ There are several ways to **set** these properties:
147
+
148
+ 1. As [environment variables](#authentication-with-environment-variables)
149
+ 1. The [programmatic approach](#programmatic-authentication)
150
+ 1. With an [external credentials file](#authentication-with-external-configuration)
151
+
152
+ ### Authentication with environment variables
116
153
 
117
154
  #### IAM authentication
118
155
 
119
- For Cloudant *IAM authentication* set the following environmental variables by replacing `<url>` and `<apikey>` with your proper [service credentials](https://cloud.ibm.com/docs/Cloudant?topic=cloudant-creating-an-ibm-cloudant-instance-on-ibm-cloud#locating-your-service-credentials). There is no need to set `CLOUDANT_AUTH_TYPE` to `IAM` because it is the default.
156
+ For Cloudant *IAM authentication*, set the following environmental variables by
157
+ replacing the `<url>` and `<apikey>` with your proper
158
+ [service credentials][service-credentials]. There is no need to set
159
+ `CLOUDANT_AUTH_TYPE` to `IAM` because it is the default.
120
160
 
121
- ```sh
161
+ ```bash
122
162
  CLOUDANT_URL=<url>
123
163
  CLOUDANT_APIKEY=<apikey>
124
164
  ```
125
165
 
126
166
  #### Session cookie authentication
127
167
 
128
- For `COUCHDB_SESSION` authentication set the following environmental variables by replacing `<url>`, `<username>` and `<password>` with your proper [service credentials](https://cloud.ibm.com/docs/Cloudant?topic=cloudant-creating-an-ibm-cloudant-instance-on-ibm-cloud#locating-your-service-credentials).
168
+ For `COUCHDB_SESSION` authentication, set the following environmental variables
169
+ by replacing the `<url>`, `<username>` and `<password>` with your proper
170
+ [service credentials][service-credentials].
129
171
 
130
- ```sh
172
+ ```bash
131
173
  CLOUDANT_AUTH_TYPE=COUCHDB_SESSION
132
174
  CLOUDANT_URL=<url>
133
175
  CLOUDANT_USERNAME=<username>
@@ -136,30 +178,66 @@ CLOUDANT_PASSWORD=<password>
136
178
 
137
179
  #### Basic authentication
138
180
 
139
- For *Basic authentication* set the following environmental variables by replacing `<url>`, `<username>` and `<password>` with your proper [service credentials](https://cloud.ibm.com/docs/Cloudant?topic=cloudant-creating-an-ibm-cloudant-instance-on-ibm-cloud#locating-your-service-credentials).
181
+ For *Basic authentication*, set the following environmental variables by
182
+ replacing the `<url>`, `<username>` and `<password>` with your proper
183
+ [service credentials][service-credentials].
140
184
 
141
- ```sh
185
+ ```bash
142
186
  CLOUDANT_AUTH_TYPE=BASIC
143
187
  CLOUDANT_URL=<url>
144
188
  CLOUDANT_USERNAME=<username>
145
189
  CLOUDANT_PASSWORD=<password>
146
190
  ```
147
191
 
148
- **Note**: We recommend using [IAM](#iam-authentication) for Cloudant and
192
+ **Note**: We recommend that you use [IAM](#iam-authentication) for Cloudant and
149
193
  [Session](#session-cookie-authentication) for CouchDB authentication.
150
194
 
195
+ ### Authentication with external configuration
196
+
197
+ To use an external configuration file, the
198
+ [Cloudant API docs](https://cloud.ibm.com/apidocs/cloudant?code=node#authentication-with-external-configuration),
199
+ or the
200
+ [general SDK usage information](https://github.com/IBM/ibm-cloud-sdk-common#using-external-configuration)
201
+ will guide you.
202
+
203
+ ### Programmatic authentication
204
+
205
+ To learn more about how to use programmatic authentication, see the related
206
+ documentation in the
207
+ [Cloudant API docs](https://cloud.ibm.com/apidocs/cloudant?code=node#programmatic-authentication)
208
+ or in the
209
+ [Node.js SDK Core document](https://github.com/IBM/node-sdk-core/blob/master/Authentication.md) about authentication.
210
+
211
+ ## Using the SDK
212
+
213
+ For general IBM Cloud SDK usage information, please see
214
+ [IBM Cloud SDK Common](https://github.com/IBM/ibm-cloud-sdk-common/blob/master/README.md).
215
+
151
216
  ### Code examples
152
217
 
218
+ The following code examples
219
+ [authenticate with the environment variables](#authenticate-with-environment-variables).
220
+
153
221
  #### 1. Retrieve information from an existing database
154
222
 
155
- This example code gathers some information about an existing database hosted on the https://examples.cloudant.com
156
- service `url`.
157
- To do this, you need to extend your environment variables with the *service url* and *authentication type* to use
158
- `NOAUTH` authentication while reaching the `animaldb` database.
159
- This step is necessary for the SDK to distinguish the `EXAMPLES` custom service name from the default service name
160
- which is `CLOUDANT`.
223
+ **Note:** This example code assumes that `animaldb` database does not exist in your account.
161
224
 
162
- ```sh
225
+ This example code gathers information about an existing database hosted on
226
+ the https://examples.cloudant.com/ service `url`. To connect, you must
227
+ extend your environment variables with the *service url* and *authentication
228
+ type* to use `NOAUTH` authentication while you connect to the `animaldb` database.
229
+ This step is necessary for the SDK to distinguish the `EXAMPLES` custom service
230
+ name from the default service name which is `CLOUDANT`.
231
+
232
+ Cloudant environment variable naming starts with a *service name* prefix that identifies your service.
233
+ By default this is `CLOUDANT`, see the settings in the
234
+ [authentication with environment variables section](#authentication-with-environment-variables).
235
+
236
+ If you would like to rename your Cloudant service from `CLOUDANT`,
237
+ you must use your defined service name as the prefix for all Cloudant related environment variables.
238
+ The code block below provides an example of instantiating a user-defined `EXAMPLES` service name.
239
+
240
+ ```bash
163
241
  EXAMPLES_URL=https://examples.cloudant.com
164
242
  EXAMPLES_AUTH_TYPE=NOAUTH
165
243
  ```
@@ -169,84 +247,94 @@ Once the environment variables are set, you can try out the code examples.
169
247
  <details open>
170
248
  <summary>TypeScript:</summary>
171
249
 
250
+ ```ts
251
+ import {CloudantV1} from "@ibm-cloud/cloudant";
252
+ ```
172
253
  [embedmd]:# (test/examples/src/ts/GetInfoFromExistingDatabase.ts /\/\/ 1./ $)
173
254
  ```ts
174
255
  // 1. Create a Cloudant client with "EXAMPLES" service name ===================
175
- const examplesClient =
176
- CloudantV1.newInstance({serviceName:"EXAMPLES"});
256
+ const client = CloudantV1.newInstance({ serviceName: 'EXAMPLES' });
177
257
 
178
258
  // 2. Get server information ==================================================
179
259
  // call service without parameters:
180
- examplesClient.getServerInformation()
181
- .then(serverInformation => {
182
- const version = serverInformation.result.version;
183
- console.log(`Server version ${version}`);
184
- });
260
+ client.getServerInformation().then((serverInformation) => {
261
+ const version = serverInformation.result.version;
262
+ console.log(`Server version ${version}`);
263
+ });
185
264
 
186
265
  // 3. Get database information for "animaldb" =================================
187
- const dbName = "animaldb";
266
+ const dbName = 'animaldb';
188
267
 
189
268
  // call service with embedded parameters:
190
- examplesClient.getDatabaseInformation({db: dbName})
191
- .then(dbInfo => {
192
- const documentCount = dbInfo.result.doc_count;
193
- const dbNameResult = dbInfo.result.db_name;
194
-
195
- // 4. Show document count in database =================================
196
- console.log(`Document count in "${dbNameResult}" database is ` +
197
- documentCount + ".");
198
- });
269
+ client.getDatabaseInformation({ db: dbName }).then((dbInfo) => {
270
+ const documentCount = dbInfo.result.doc_count;
271
+ const dbNameResult = dbInfo.result.db_name;
272
+
273
+ // 4. Show document count in database =================================
274
+ console.log(
275
+ `Document count in "${dbNameResult}" database is ` + documentCount + '.'
276
+ );
277
+ });
199
278
 
200
279
  // 5. Get zebra document out of the database by document id ===================
201
- const getDocParams:
202
- CloudantV1.GetDocumentParams = {db: dbName, docId: "zebra"};
280
+ const getDocParams: CloudantV1.GetDocumentParams = {
281
+ db: dbName,
282
+ docId: 'zebra',
283
+ };
203
284
 
204
285
  // call service with predefined parameters:
205
- examplesClient.getDocument(getDocParams)
206
- .then(documentAboutZebra => {
207
- // result object is defined as a Document here:
208
- const result: CloudantV1.Document = documentAboutZebra.result;
209
- console.log("Document retrieved from database:\n" +
210
- JSON.stringify(result, null, 2));
211
- });
286
+ client.getDocument(getDocParams).then((documentAboutZebra) => {
287
+ // result object is defined as a Document here:
288
+ const result: CloudantV1.Document = documentAboutZebra.result;
289
+ console.log(
290
+ 'Document retrieved from database:\n' + JSON.stringify(result, null, 2)
291
+ );
292
+ });
212
293
  ```
213
294
  </details>
214
295
 
215
296
  <details>
216
297
  <summary>JavaScript:</summary>
217
298
 
299
+ ```js
300
+ const { CloudantV1 } = require('@ibm-cloud/cloudant');
301
+ ```
218
302
  [embedmd]:# (test/examples/src/js/GetInfoFromExistingDatabase.js /const getInfoFromExistingDatabase/ /getInfoFromExistingDatabase\(\);\n\}/)
219
303
  ```js
220
304
  const getInfoFromExistingDatabase = async () => {
221
305
  // 1. Create a Cloudant client with "EXAMPLES" service name ===================
222
- const examplesClient = CloudantV1.newInstance({ serviceName: 'EXAMPLES' });
306
+ const client = CloudantV1.newInstance({ serviceName: 'EXAMPLES' });
223
307
 
224
308
  // 2. Get server information ==================================================
225
309
  // call service without parameters:
226
- const version = (await examplesClient.getServerInformation()).result.version;
310
+ const version = (await client.getServerInformation()).result.version;
227
311
  console.log(`Server version ${version}`);
228
312
 
229
313
  // 3. Get database information for "animaldb" =================================
230
314
  const dbName = 'animaldb';
231
315
 
232
316
  // call service with embedded parameters:
233
- const dbInfo = await examplesClient.getDatabaseInformation({ db: dbName });
317
+ const dbInfo = await client.getDatabaseInformation({ db: dbName });
234
318
  const documentCount = dbInfo.result.doc_count;
235
319
  const dbNameResult = dbInfo.result.db_name;
236
320
 
237
321
  // 4. Show document count in database =================================
238
- console.log(`Document count in "${dbNameResult}" database is ` + documentCount + '.');
322
+ console.log(
323
+ `Document count in "${dbNameResult}" database is ` + documentCount + '.'
324
+ );
239
325
 
240
326
  // 5. Get zebra document out of the database by document id ===================
241
327
  const getDocParams = { db: dbName, docId: 'zebra' };
242
328
 
243
329
  // call service with predefined parameters:
244
- const documentAboutZebra = await examplesClient.getDocument(getDocParams);
330
+ const documentAboutZebra = await client.getDocument(getDocParams);
245
331
 
246
332
  // result object is defined as a Document here:
247
333
  const result = documentAboutZebra.result;
248
334
 
249
- console.log('Document retrieved from database:\n' + JSON.stringify(result, null, 2));
335
+ console.log(
336
+ 'Document retrieved from database:\n' + JSON.stringify(result, null, 2)
337
+ );
250
338
  };
251
339
 
252
340
  if (require.main === module) {
@@ -256,8 +344,7 @@ if (require.main === module) {
256
344
 
257
345
  </details>
258
346
 
259
- The result of the code is similar to the following output.
260
- The order of the output lines may change due to the asynchronicity.
347
+ When you run the code, you see a result similar to the following output.
261
348
 
262
349
  [embedmd]:# (test/examples/output/GetInfoFromExistingDatabase.txt)
263
350
  ```txt
@@ -279,87 +366,87 @@ Document retrieved from database:
279
366
 
280
367
  #### 2. Create your own database and add a document
281
368
 
282
- Now comes the exciting part of creating your own `orders` database and adding a document
283
- about *Bob Smith* with your own [IAM](#iam-authentication) or [Basic](#basic-authentication) service credentials.
369
+ **Note:** This example code assumes that `orders` database does not exist in your account.
370
+
371
+ Now comes the exciting part, you create your own `orders` database and add a document about *Bob Smith* with your own [IAM](#iam-authentication) or
372
+ [Basic](#basic-authentication) service credentials.
373
+
374
+ <details>
375
+ <summary>Create code example</summary>
284
376
 
285
377
  <details open>
286
378
  <summary>TypeScript:</summary>
287
379
 
380
+ ```ts
381
+ import {CloudantV1} from "@ibm-cloud/cloudant";
382
+ ```
288
383
  [embedmd]:# (test/examples/src/ts/CreateDbAndDoc.ts /interface/ $)
289
384
  ```ts
290
385
  interface OrderDocument extends CloudantV1.Document {
291
- name?: string;
292
- joined?: string;
293
- _id: string;
294
- _rev?: string;
386
+ name?: string;
387
+ joined?: string;
388
+ _id: string;
389
+ _rev?: string;
295
390
  }
296
391
 
297
392
  // 1. Create a client with `CLOUDANT` default service name ================
298
393
  const client = CloudantV1.newInstance({});
299
394
 
300
395
  // 2. Create a database =======================================================
301
- const exampleDbName = "orders";
396
+ const exampleDbName = 'orders';
302
397
 
303
398
  // Try to create database if it doesn't exist
304
- const createDb = client.putDatabase({db: exampleDbName})
305
- .then(putDatabaseResult => {
306
- if (putDatabaseResult.result.ok) {
307
- console.log(`"${exampleDbName}" database created."`);
308
- }
309
- })
310
- .catch(err => {
311
- if (err.code === 412){
312
- console.log("Cannot create \"" + exampleDbName +
313
- "\" database, it already exists.");
314
- }
315
- });
399
+ const createDb = client
400
+ .putDatabase({ db: exampleDbName })
401
+ .then((putDatabaseResult) => {
402
+ if (putDatabaseResult.result.ok) {
403
+ console.log(`"${exampleDbName}" database created."`);
404
+ }
405
+ })
406
+ .catch((err) => {
407
+ if (err.code === 412) {
408
+ console.log(
409
+ 'Cannot create "' + exampleDbName + '" database, it already exists.'
410
+ );
411
+ }
412
+ });
316
413
 
317
414
  // 3. Create a document =======================================================
318
415
  // Create a document object with "example" id
319
- const exampleDocId = "example";
416
+ const exampleDocId = 'example';
320
417
 
321
418
  // set required _id property on exampleDocument:
322
- const exampleDocument: OrderDocument = {_id: exampleDocId};
419
+ const exampleDocument: OrderDocument = { _id: exampleDocId };
323
420
 
324
421
  // Add "name" and "joined" fields to the document
325
- exampleDocument.name = "Bob Smith";
326
- exampleDocument.joined = "2019-01-24T10:42:99.000Z";
422
+ exampleDocument.name = 'Bob Smith';
423
+ exampleDocument.joined = '2019-01-24T10:42:99.000Z';
327
424
 
328
- /* Try to get the document and set revision of exampleDocument to the
329
- latest one if it previously existed in the database */
425
+ // Save the document in the database
330
426
  createDb.then(() => {
331
- client.getDocument({db: exampleDbName, docId: exampleDocId})
332
- .then(documentInfo => {
333
- exampleDocument._rev = documentInfo.result._rev;
334
- console.log("The document revision for" + exampleDocId +
335
- "is set to " + exampleDocument._rev);
336
- })
337
- .catch(err => {
338
- if (err.code === 404) {
339
- // Document does not exist in database
340
- }
341
- })
342
- .finally(() => {
343
- // Save the document in the database
344
- client.postDocument({
345
- db: exampleDbName,
346
- document: exampleDocument
347
- }
348
- ).then(createDocumentResponse => {
349
- // Keep track with the revision number of the document object
350
- exampleDocument._rev = createDocumentResponse.result.rev;
351
- console.log("You have created the document:\n" +
352
- JSON.stringify(exampleDocument, null, 2));
353
- });
354
- });
427
+ client
428
+ .postDocument({
429
+ db: exampleDbName,
430
+ document: exampleDocument,
431
+ })
432
+ .then((createDocumentResponse) => {
433
+ // Keep track with the revision number of the document object
434
+ exampleDocument._rev = createDocumentResponse.result.rev;
435
+ console.log(
436
+ 'You have created the document:\n' +
437
+ JSON.stringify(exampleDocument, null, 2)
438
+ );
439
+ });
355
440
  });
356
441
  ```
357
-
358
442
  </details>
359
443
 
360
444
  <details>
361
445
  <summary>JavaScript:</summary>
362
446
 
447
+ ```js
448
+ const { CloudantV1 } = require('@ibm-cloud/cloudant');
449
+ ```
363
450
  [embedmd]:# (test/examples/src/js/CreateDbAndDoc.js /const createDbAndDoc/ /createDbAndDoc\(\);\n\}/)
364
451
  ```js
365
452
  const createDbAndDoc = async () => {
@@ -381,7 +468,9 @@ const createDbAndDoc = async () => {
381
468
  }
382
469
  } catch (err) {
383
470
  if (err.code === 412) {
384
- console.log('Cannot create "' + exampleDbName + '" database, it already exists.');
471
+ console.log(
472
+ 'Cannot create "' + exampleDbName + '" database, it already exists.'
473
+ );
385
474
  }
386
475
  }
387
476
 
@@ -395,44 +484,29 @@ const createDbAndDoc = async () => {
395
484
  exampleDocument['name'] = 'Bob Smith';
396
485
  exampleDocument.joined = '2019-01-24T10:42:99.000Z';
397
486
 
398
- /* Try to get the document and set revision of exampleDocument to the
399
- latest one if it previously existed in the database */
400
- try {
401
- exampleDocument._rev = (
402
- await client.getDocument({
403
- db: exampleDbName,
404
- docId: exampleDocId,
405
- })
406
- ).result._rev;
407
- console.log(
408
- 'The document revision for "' + exampleDocId + '" is set to ' + exampleDocument._rev
409
- );
410
- } catch (err) {
411
- if (err.code === 404) {
412
- // Document does not exist in database
413
- }
414
- } finally {
415
- // Save the document in the database
416
- const createDocumentResponse = await client.postDocument({
417
- db: exampleDbName,
418
- document: exampleDocument,
419
- });
420
-
421
- // Keep track with the revision number of the document object
422
- exampleDocument._rev = createDocumentResponse.result.rev;
423
- console.log('You have created the document:\n' + JSON.stringify(exampleDocument, null, 2));
424
- }
487
+ // Save the document in the database
488
+ const createDocumentResponse = await client.postDocument({
489
+ db: exampleDbName,
490
+ document: exampleDocument,
491
+ });
492
+
493
+ // Keep track with the revision number of the document object
494
+ exampleDocument._rev = createDocumentResponse.result.rev;
495
+ console.log(
496
+ 'You have created the document:\n' +
497
+ JSON.stringify(exampleDocument, null, 2)
498
+ );
425
499
  };
426
500
 
427
501
  if (require.main === module) {
428
502
  createDbAndDoc();
429
503
  }
430
504
  ```
431
-
432
505
  </details>
433
506
 
434
- The result of the code is similar to the following output.
435
- The order of the output lines may change due to the asynchronicity.
507
+
508
+ </details>
509
+ When you run the code, you see a result similar to the following output.
436
510
 
437
511
  [embedmd]:# (test/examples/output/CreateDbAndDoc.txt)
438
512
  ```txt
@@ -448,69 +522,82 @@ You have created the document:
448
522
 
449
523
  #### 3. Update your previously created document
450
524
 
451
- **Note**: this example code assumes that you have created both the `orders` database and the `example`
452
- document by [running this previous example code](#2-create-your-own-database-and-add-a-document)
453
- successfully, otherwise you get the `Cannot update document because either "orders" database or
454
- "example" document was not found.` message.
525
+ **Note**: This example code assumes that you have created both the `orders`
526
+ database and the `example` document by
527
+ [running the previous example code](#2-create-your-own-database-and-add-a-document)
528
+ successfully. Otherwise, the following error message occurs, "Cannot update document because either 'orders'
529
+ database or 'example' document was not found."
530
+
531
+ <details>
532
+ <summary>Update code example</summary>
455
533
 
456
534
  <details open>
457
535
  <summary>TypeScript:</summary>
458
536
 
537
+ ```ts
538
+ import {CloudantV1} from "@ibm-cloud/cloudant";
539
+ ```
459
540
  [embedmd]:# (test/examples/src/ts/UpdateDoc.ts /interface/ $)
460
541
  ```ts
461
542
  interface OrderDocument extends CloudantV1.Document {
462
- address?: string;
463
- joined?: string;
464
- _id?: string;
465
- _rev?: string;
543
+ address?: string;
544
+ joined?: string;
545
+ _id?: string;
546
+ _rev?: string;
466
547
  }
467
548
 
468
549
  // 1. Create a client with `CLOUDANT` default service name ================
469
550
  const client = CloudantV1.newInstance({});
470
551
  // 2. Update the document =====================================================
471
552
  // Set the options to get the document out of the database if it exists
472
- const exampleDbName = "orders";
553
+ const exampleDbName = 'orders';
473
554
 
474
555
  // Try to get the document if it previously existed in the database
475
- const getDocParams: CloudantV1.GetDocumentParams =
476
- {docId: "example", db: exampleDbName};
477
-
478
- client.getDocument(getDocParams)
479
- .then(docResult => {
480
- // using OrderDocument on getDocument result:
481
- const document: OrderDocument = docResult.result;
482
-
483
- // Add Bob Smith's address to the document
484
- document.address = "19 Front Street, Darlington, DL5 1TY";
485
-
486
- // Remove the joined property from document object
487
- delete document.joined;
488
-
489
- // Update the document in the database
490
- client.postDocument({db: exampleDbName, document})
491
- .then(res => {
492
- // Keeping track with the revision number of the document object:
493
- document._rev = res.result.rev;
494
- console.log("You have updated the document:\n" +
495
- JSON.stringify(document, null, 2));
496
- });
497
- })
498
- .catch(err => {
499
- if (err.code === 404) {
500
- console.log(
501
- "Cannot update document because either \"" +
502
- exampleDbName + "\" database or the \"example\" " +
503
- "document was not found."
504
- );
505
- }
556
+ const getDocParams: CloudantV1.GetDocumentParams = {
557
+ docId: 'example',
558
+ db: exampleDbName,
559
+ };
560
+
561
+ client
562
+ .getDocument(getDocParams)
563
+ .then((docResult) => {
564
+ // using OrderDocument on getDocument result:
565
+ const document: OrderDocument = docResult.result;
566
+
567
+ // Add Bob Smith's address to the document
568
+ document.address = '19 Front Street, Darlington, DL5 1TY';
569
+
570
+ // Remove the joined property from document object
571
+ delete document.joined;
572
+
573
+ // Update the document in the database
574
+ client.postDocument({ db: exampleDbName, document }).then((res) => {
575
+ // Keeping track with the revision number of the document object:
576
+ document._rev = res.result.rev;
577
+ console.log(
578
+ 'You have updated the document:\n' + JSON.stringify(document, null, 2)
579
+ );
506
580
  });
581
+ })
582
+ .catch((err) => {
583
+ if (err.code === 404) {
584
+ console.log(
585
+ 'Cannot update document because either "' +
586
+ exampleDbName +
587
+ '" database or the "example" ' +
588
+ 'document was not found.'
589
+ );
590
+ }
591
+ });
507
592
  ```
508
-
509
593
  </details>
510
594
 
511
595
  <details>
512
596
  <summary>JavaScript:</summary>
513
597
 
598
+ ```js
599
+ const { CloudantV1 } = require('@ibm-cloud/cloudant');
600
+ ```
514
601
  [embedmd]:# (test/examples/src/js/UpdateDoc.js /const updateDoc/ /updateDoc\(\);\n\}/)
515
602
  ```js
516
603
  const updateDoc = async () => {
@@ -543,7 +630,9 @@ const updateDoc = async () => {
543
630
  })
544
631
  ).result.rev;
545
632
 
546
- console.log('You have updated the document:\n' + JSON.stringify(document, null, 2));
633
+ console.log(
634
+ 'You have updated the document:\n' + JSON.stringify(document, null, 2)
635
+ );
547
636
  } catch (err) {
548
637
  if (err.code === 404) {
549
638
  console.log(
@@ -560,17 +649,18 @@ if (require.main === module) {
560
649
  updateDoc();
561
650
  }
562
651
  ```
563
-
564
652
  </details>
565
653
 
566
- The result of the code is similar to the following output.
654
+
655
+ </details>
656
+ When you run the code, you see a result similar to the following output.
567
657
 
568
658
  [embedmd]:# (test/examples/output/UpdateDoc.txt)
569
659
  ```txt
570
660
  You have updated the document:
571
661
  {
572
662
  "_id": "example",
573
- "_rev": "2-70476cf75eb02f55c6c4061aa6941ec8",
663
+ "_rev": "2-4e2178e85cffb32d38ba4e451f6ca376",
574
664
  "name": "Bob Smith",
575
665
  "address": "19 Front Street, Darlington, DL5 1TY"
576
666
  }
@@ -578,22 +668,29 @@ You have updated the document:
578
668
 
579
669
  #### 4. Delete your previously created document
580
670
 
581
- **Note**: this example code assumes that you have created both the `orders` database and the `example`
582
- document by [running this previous example code](#2-create-your-own-database-and-add-a-document)
583
- successfully, otherwise you get the `Cannot delete document because either "orders" database or
584
- "example" document was not found.` message.
671
+ **Note**: This example code assumes that you have created both the `orders`
672
+ database and the `example` document by
673
+ [running the previous example code](#2-create-your-own-database-and-add-a-document)
674
+ successfully. Otherwise, the following error message occurs, "Cannot delete document because either 'orders'
675
+ database or 'example' document was not found."
676
+
677
+ <details>
678
+ <summary>Delete code example</summary>
585
679
 
586
680
  <details open>
587
681
  <summary>TypeScript:</summary>
588
682
 
683
+ ```ts
684
+ import {CloudantV1} from "@ibm-cloud/cloudant";
685
+ ```
589
686
  [embedmd]:# (test/examples/src/ts/DeleteDoc.ts /interface/ $)
590
687
  ```ts
591
688
  interface OrderDocument extends CloudantV1.Document {
592
- name?: string;
593
- address?: string;
594
- joined?: string;
595
- _id?: string;
596
- _rev?: string;
689
+ name?: string;
690
+ address?: string;
691
+ joined?: string;
692
+ _id?: string;
693
+ _rev?: string;
597
694
  }
598
695
 
599
696
  // 1. Create a client with `CLOUDANT` default service name ================
@@ -601,40 +698,49 @@ const client = CloudantV1.newInstance({});
601
698
 
602
699
  // 2. Delete the document =============================================
603
700
  // Set the options to get the document out of the database if it exists
604
- const exampleDbName = "orders";
605
- const exampleDocId = "example";
701
+ const exampleDbName = 'orders';
702
+ const exampleDocId = 'example';
606
703
 
607
704
  // Try to get the document if it previously existed in the database
608
- const getDocParams: CloudantV1.GetDocumentParams =
609
- {docId: exampleDocId, db: exampleDbName};
610
-
611
- client.getDocument(getDocParams)
612
- .then(docResult => {
613
- const document: OrderDocument = docResult.result;
614
-
615
- client.deleteDocument({
616
- db: exampleDbName,
617
- docId: document._id,
618
- rev: document._rev}).then(() => {
619
- console.log("You have deleted the document.");
620
- });
621
- })
622
- .catch(err => {
623
- if (err.code === 404) {
624
- console.log(
625
- "Cannot delete document because either \"" +
626
- exampleDbName + "\" database or the \"example\" " +
627
- "document was not found."
628
- );
629
- }
630
- });
631
- ```
705
+ const getDocParams: CloudantV1.GetDocumentParams = {
706
+ docId: exampleDocId,
707
+ db: exampleDbName,
708
+ };
709
+
710
+ client
711
+ .getDocument(getDocParams)
712
+ .then((docResult) => {
713
+ const document: OrderDocument = docResult.result;
632
714
 
715
+ client
716
+ .deleteDocument({
717
+ db: exampleDbName,
718
+ docId: document._id,
719
+ rev: document._rev,
720
+ })
721
+ .then(() => {
722
+ console.log('You have deleted the document.');
723
+ });
724
+ })
725
+ .catch((err) => {
726
+ if (err.code === 404) {
727
+ console.log(
728
+ 'Cannot delete document because either "' +
729
+ exampleDbName +
730
+ '" database or the "example" ' +
731
+ 'document was not found.'
732
+ );
733
+ }
734
+ });
735
+ ```
633
736
  </details>
634
737
 
635
738
  <details>
636
739
  <summary>JavaScript:</summary>
637
740
 
741
+ ```js
742
+ const { CloudantV1 } = require('@ibm-cloud/cloudant');
743
+ ```
638
744
  [embedmd]:# (test/examples/src/js/DeleteDoc.js /const deleteDoc/ /deleteDoc\(\);\n\}/)
639
745
  ```js
640
746
  const deleteDoc = async () => {
@@ -677,51 +783,65 @@ if (require.main === module) {
677
783
  deleteDoc();
678
784
  }
679
785
  ```
680
-
681
786
  </details>
682
787
 
683
- The result of the code is the following output.
788
+
789
+ </details>
790
+ When you run the code, you see the following output.
684
791
 
685
792
  [embedmd]:# (test/examples/output/DeleteDoc.txt)
686
793
  ```txt
687
794
  You have deleted the document.
688
795
  ```
689
796
 
690
- ## Using the SDK
797
+ ### Error handling
798
+
799
+ For sample code on handling errors, see
800
+ [Cloudant API docs](https://cloud.ibm.com/apidocs/cloudant?code=node#error-handling).
801
+
802
+ ### Raw IO
803
+
804
+ For endpoints that read or write document content it is possible to bypass
805
+ usage of the built-in models and send or receive a bytes response.
806
+ For examples of using byte streams, see the API reference documentation
807
+ ("Example request as a stream" section).
691
808
 
692
- For general SDK usage information, please see
693
- [this link](https://github.com/IBM/ibm-cloud-sdk-common/blob/master/README.md)
809
+ - [Bulk modify multiple documents in a database](https://cloud.ibm.com/apidocs/cloudant?code=node#postbulkdocs)
810
+ - [Query a list of all documents in a database](https://cloud.ibm.com/apidocs/cloudant?code=node#postalldocs)
811
+ - [Query the database document changes feed](https://cloud.ibm.com/apidocs/cloudant?code=node#postchanges)
812
+
813
+ ### Further resources
814
+
815
+ - [Cloudant API docs](https://cloud.ibm.com/apidocs/cloudant?code=node):
816
+ API examples for Cloudant Node.js SDK.
817
+ - [Cloudant docs](https://cloud.ibm.com/docs/services/Cloudant?topic=cloudant-overview#overview):
818
+ The official documentation page for Cloudant.
819
+ - [Cloudant Learning Center](https://developer.ibm.com/clouddataservices/docs/compose/cloudant/):
820
+ The official learning center with several useful videos which help you use
821
+ Cloudant successfully.
822
+ - [Cloudant blog](https://blog.cloudant.com/):
823
+ Many useful articles about how to optimize Cloudant for common problems.
694
824
 
695
825
  ## Questions
696
826
 
697
- If you are having difficulties using this SDK or have a question about the IBM Cloud services,
698
- please ask a question at
827
+ If you are having difficulties using this SDK or have a question about the
828
+ IBM Cloud services, ask a question on
699
829
  [Stack Overflow](http://stackoverflow.com/questions/ask?tags=ibm-cloud).
700
830
 
701
831
  ## Issues
702
832
 
703
- If you encounter an issue with the SDK, you are welcome to submit
704
- a [bug report](https://github.com/IBM/cloudant-node-sdk/issues).
705
- Before that, please search for similar issues. It's possible someone has
706
- already encountered this issue.
707
-
708
- ## Further resources
709
-
710
- - [Cloudant API docs](https://cloud.ibm.com/apidocs/cloudant?code=node): API examples for Cloudant Node.js SDK.
711
- - [Cloudant docs](https://cloud.ibm.com/docs/services/Cloudant?topic=cloudant-overview#overview): The official documentation page for Cloudant.
712
- - [Cloudant Learning Center](https://developer.ibm.com/clouddataservices/docs/compose/cloudant/): The official learning center with several useful videos which help you to use Cloudant successfully.
713
- - [Cloudant blog](https://blog.cloudant.com/): Many useful articles how to optimize Cloudant for common problems.
833
+ If you encounter an issue with the project, you are welcome to submit a
834
+ [bug report](https://github.com/IBM/cloudant-node-sdk/issues).
835
+ Before you submit a bug report, search for similar issues. It's possible that your issue has already been reported.
714
836
 
715
- ## Open source @ IBM
837
+ ## Open source at IBM
716
838
 
717
- Find more open source projects on the [IBM Github Page](http://ibm.github.io/)
839
+ Find more open source projects on the [IBM Github](http://ibm.github.io/) page.
718
840
 
719
841
  ## Contributing
720
842
 
721
- See [CONTRIBUTING](CONTRIBUTING.md).
843
+ For more information, see [CONTRIBUTING](CONTRIBUTING.md).
722
844
 
723
845
  ## License
724
846
 
725
- This project is released under the Apache 2.0 license.
726
- The license's full text can be found in
727
- [LICENSE](LICENSE).
847
+ This SDK is released under the Apache 2.0 license. To read the full text of the license, see [LICENSE](LICENSE).