3.3.11.Building support for Partial Responses

  • Partial Responses

    • "API consumer" in control of response

    • 例如mobile的使用者可能不需要取得完整的資料, Partial Responses可以讓使用者指定特定的欄位

  • Benefits

    • Better performance & optimized resource usage

      • CPU, Memory, Bandwidth

    • API consumer controls the granularity

    • Common API version for all consumers

      • to support multiple devices, use cases - form factors

  • Specifiction

    • Depends on the platform/language/DB

    • Linkedin: /people: (id, first-name, last-name)

    • facebook: /friend?fields=id,name,picture

    • Pinterest: /pins?fields=id,link,creator(first_name)

  • Requirements

    • mlab

      • Add collection -> 新增一個叫hotels的collection

      • Add database user -> 新增一個叫xxx的user

      • collection-> index -> add index

        • { "name": 1}, 勾選unique

    • source code from github

      • 1.clone repository

        git clone https://github.com/acloudfan/REST-API-Course.git
        cd REST-API-COURSE/
        git checkout partialresponse
        npm install
      • 2.將資料寫到DB

        • 設定連線字串

          • 到mlab的database頁面下, 複製連線字串

          • 開啟專案, 修改tests/TestHotelsDBOps.js的process.env.DB_URI

          • 開啟檢視/ 偵錯主控台/ 終端機, 輸入

               node tests/TestHotelsDBOps
      • 3.程式碼解析

     module.exports = function(router){
    'use strict';

    router.route(URI).get(function(req, res,next){
        console.log("GET Hotels")

        //1. fields
        var fields ={}
        if(req.query && req.query.fields !== undefined){
           fields =  createFields(req.query.fields)
        }

        //2. Setup options
        var options = {fields:fields}
        console.log(options)

        //3. execute the query
        var criteria = {}
        db.select(criteria, options, function(err,docs){

            if(err){
                console.log(err)
                res.status(500)
                res.send("Error connecting to db")
            } else {
                if(docs.length == 0){
                    res.status(404)
                }
                console.log("Retrieved hotels = %d",docs.length)
                res.send(docs)
            }
        });
    });
    }

    // RETRIEVE hotels packages based on criteria & fields
// https://docs.mongodb.com/manual/reference/method/db.collection.find/#find-projection
// options = {
//    fields: {/** Projection **/}
// }
exports.select = function (criteria,options, callback) {
    model.Hotels.find(criteria, function (err, data) {
        callback(err, data)
    }).select(options.fields)
}

Last updated

Was this helpful?