# 第四章 如何綁定一個服務 - 資料庫服務
學習目標
1. 建立 "Cloudant" 服務
2. 整合 "Cloudant" 服務
## 1. 建立 "Cloudant" 服務
step 1: Login IBM Cloud https://cloud.ibm.com/login
step 2: 點選 "型錄" , 然後在左邊的選單中, 點選 "服務" 後,再勾選 "資料庫", 就可以看到 data services 相關的服務.
step 3: 點選 "Cloudant" 服務. "選取地區" 用預設值 "達拉斯", 將服務名稱取名為 "cloudant-ntust" 後,點選右邊的 "建立" 按鈕.
step 4: 點選剛建立好的 instance, 接著建立 service credential. 點選左邊選單中的 "服務認證", 然後再點選右上方 "新建認證", 填寫認證名稱 "API_CRED", 其餘用預設值即可.
step 5: 將產生的金鑰儲存到專案的資料夾中.
step 6: 點選左邊選單中的 "連線", 然後再點選右上方 "建立連線", 即可看到目前可選用的 Cloud Foundry 應用程式, 點選欲連接的應用程式, 並點選 "下一個" 按鍵, 保留預設值, 按 "建立" 按鍵, 並確認 "重新編譯打包" 按鈕.
step 7: 在狀態變為 "已啟動" 的時候, 可以從應用程式的 url 去驗證.
## 2. 整合 "Cloudant" 服務
reference API doc:
https://cloud.ibm.com/docs/node?topic=node-cloudant (recommended)
https://cloud.ibm.com/apidocs/cloudant?code=node
step 1:
```
PS D:\cloud109> mkdir dataService
PS D:\cloud109> cd dataservice
PS D:\cloud109\dataservice> npm init
```
step 2: Installing SDK
Begin with your own Node.js project, and define this work as your dependency. In other words, put IBM Cloudant in your package.json dependencies. Use the npm package manager from the command line to install the SDK:
```
PS D:\cloud109\dataservice> npm install --save @cloudant/cloudant
```
step 3: Initializing the SDK
After you initialize the SDK in your app, you can use IBM Cloudant to store data. To initialize your connection, enter your credentials and provide a callback function to run when everything is ready.
(1) Load the client library by adding the following require definition to your app.js file
```javascript=
var Cloudant = require('@cloudant/cloudant');
cloudant();
async function cloudant(){
console.log("cloudant tutorial");
try{
console.log("Creating cloudant connection....");
}catch(err){
console.error(`Error => ${err}`);
}
}
```
(2) Initialize the client library by supplying your credentials. Use the iamauth plug-in to create a database client with an IAM API key.
```javascript=
console.log("Creating cloudant connection....");
var cloudant = new Cloudant({
url: 'https://examples.cloudant.com',
plugins: {
iamauth: {
iamApiKey: 'xxxxxxxxxx'
}
}
});
console.log("Created cloudant connection....");
```
(3) List the databases by adding the following code to your app.js file
```javascript=
console.log("Getting cloudant dbs...");
let allDBS = await cloudant.db.list();
console.log("cloudant dbs listing...");
console.log(`Cloudant dbs [${allDBS}]`);
```
(4) 從 IBM Cloud console 開啟 Cloudant 資料庫 dashboard, 並創建資料庫取名為 "animal".
step 4: 連接資料庫
```javascript=
console.log("Setting the db that we are going to use!!");
const db = cloudant.db.use("animals");
```
step 5: Managing data with basic operations
These basic operations illustrate the actions to create, read, update, and delete your documents by using the initialized client.
(1) 創建一個檔案
```javascript=
const doc0 = { "_id":"canidae:dog", "name":"Dog", "latin":"Canis lupus familiaris"}
let res="";
res = await db.insert(doc0);
console.log(res);
console.log(`Added doc to database ${res}`);
```
(2) 讀取一個檔案
```javascript=
console.log("Get doc from database");
res = await db.get(doc0._id);
console.log(res);
```
(3) 修改檔案
```javascript=
console.log("Get doc from database");
res = await db.get(doc0._id);
console.log(res);
doc0["_rev"]=res._rev;
doc0.latin = "Canis Lupus No Familiaris (Edited)"
res = await db.insert(doc0);
console.log(`Edited doc to database ${res}`);
```
(4) 一次儲存多筆資料
```javascript=
const bulk = [
{ "_id":"felis:wildcat", "name":"Wildcat", "latin":"Felis Silvestris"},
{ "_id":"canidae:wolf", "name":"Wolf", "latin":"Canis lupus familiaris"},
{ "_id":"felis:cat", "name":"Cat", "latin":"Felis Catus"}
]
let res="";
res = await db.bulk({docs:bulk});
console.log(res);
console.log(`Added doc to database ${res}`);
```
(5) Getting the docs by partition
```javascript=
console.log("Getting the docs by partition")
res = await db.partitionedList("canidae",{include_docs:false});
console.log(res);
```
(6) Getting all docs
```javascript=
console.log("Getting all docs");
res = await db.list({include_docs:true});
console.log(res);
```
(7) Delete a document
```javascript=
console.log("Delete doc");
res = await db.destroy("felis:wildcat","1-6b4e1b3f460d8aa6fd06fc9dde2192aa");
console.log(res);
```
更多的參考資料: https://www.npmjs.com/package/@cloudant/cloudant