[REST] REST API 的 client 程式開發 (node-rest-client)

在之前的文章中, 我們介紹了如何建立一個 json-server,
通常, 這樣的架構是為了作為 RESTful API 的介面,
在文章的安裝步驟中, 事實上, 有暗示此 JSON server 是以 NodeJs 的架構撰寫,
考慮到 NodeJS 對網頁端的支援, 也的確是一個合適的選擇.

傳送到 json-server 的資訊將被放到一個 .json 文件中暫存,
然而, 考慮到 json-server 並非設計作為資料庫使用,
當暫存資料過大時, 就會讓讀取/寫入失去效率,
因此, 我們需要寫一隻程式, 從 json-server 中取值, 處理, 再刪除數值,
架構如下圖所示:

資料處理的架構

當然, 更好一點的架構是直接用 NodeJs 來架設 REST API Server,
但考慮到平台的熟悉程度, 還是先用寫好的套裝程式來改,
應該比較穩定一些, 雖然犧牲不少效率...

在實作範例中, 我們使用 node-rest-client 作為開發套件,
node-rest-client 建立在 NodeJs 之上, 可以參考:
https://www.npmjs.com/package/node-rest-client
在其官網上, 有許多範例, 因此就不再多述如何安裝 node-rest-client,
以及每一個 REST 函數的呼叫,
在進入程式之前, 只提醒兩件事情:

  1. NodeJs 有原生的平行化架構, 因此, 當使用多個 client 時,
    要注意每個 client 的執行並不會依照程式的順序.
  2. 相同的, 由於平行化架構, global variable 的存取順序可能和預期不同,
    要自己想好順序, 並包在同一個 client 中.

因此, 本程式的目標流程有以下三個:
讀取 json 總數 => 取出最後一個 json 物件 => 刪除最後一個 json 物件
以下是所實作的程式:

var Client = require('node-rest-client').Client;
var client = new Client();

// get the number of json object
// refer to the "slice" method in the  json-server
client.get("http://localhost:3000/posts?_start=1&_end=100", function (data, response) {
    // parsed response body as js object
    // console.log(data);
    // raw response
    // console.log(response);

    var totalCount = 100;
    totalCount = response.headers["x-total-count"];
    console.log("check: " + totalCount);

    // GET the last json report
    var getClient = new Client();

    var getURL = "http://localhost:3000/comments/" + totalCount;
    console.log("GET URL: " + getURL);

    getClient.get(getURL, function (getData, getResponse) {
        console.log(getData);
        // do something here
        // collect the information from json format
        // save the information into SQL database

        var deleteClient = new Client();

        deleteClient.delete(getURL, function (delData, delResponse) {
            console.log("DELETE URL: " + getURL);
        });
    });
});


以下是執行的成果:

$ node TestDB.js
check: 1
GET URL: http://localhost:3000/comments/1
{ id: 1, body: 'some comment', postId: 1 }
DELETE URL: http://localhost:3000/comments/1

留言

熱門文章

LTE筆記: RSRP, RSSI and RSRQ

[WiFi] WiFi 網路的識別: BSS, ESS, SSID, ESSID, BSSID

LTE筆記: 波束成型 (beamforming) 和天線陣列