SAPUI5 (23) - 使用mock server模擬oData提供者

模擬服務器(mock server)的作用

所有的應用程序都涉及CRUD操作,openui5在真實的場景中是通過oData和后端SAP系統交互。但在開發過程中,為了測試的需要,可以使用模擬服務器,openui5將模擬服務器稱作mock server。模擬服務器的基本功能是模擬oData數據提供者,截獲應用程序的對服務器端的htpp或https請求,并傳回模擬請求的回應。從openui5開發的這一側來看,可以降低與真實后端的耦合。

mock server簡單介紹

openui5有自己的mocke server模塊,但我這里參照《SAPUI5 Comprehensive Guide》一書,使用另外一個框架:github上的fakerest,基于sinon(地址:點擊)。支持CRUD操作,基本使用方法如下:

    1. FakeRest.min.js文件在webapp的service文件夾下。并添加對js文件的引用。
<script src="../service/FakeRest.min.js"></script>
    1. mockServerTest.html文件放在webapp下的test文件夾下。用于測試代碼。
    1. 加載sinon模塊
jQuery.sap.require("sap.ui.thirdparty.sinon");
    1. 加載數據并初始化fake server和sinon server
var data = {
    'authors': [
        { id: 0, first_name: 'Leo', last_name: 'Tolstoi' },
        { id: 1, first_name: 'Jane', last_name: 'Austen' }
    ],
    'books': [
        { id: 0, author_id: 0, title: 'Anna Karenina' },
        { id: 1, author_id: 0, title: 'War and Peace' },
        { id: 2, author_id: 1, title: 'Pride and Prejudice' },
        { id: 3, author_id: 1, title: 'Sense and Sensibility' }
    ],
    'settings': {
        language: 'english',
        preferred_format: 'hardback',
    }
};
    
// initialize fake REST server
var restServer = new FakeRest.Server();
restServer.init(data);

// use sinon.js to monkey-patch XmlHttpRequest
var server = sinon.fakeServer.create();
server.respondWith(restServer.getHandler());
    1. 在mock server中實現增刪改查操作
// 使用GET請求查詢所有的author
var req = new XMLHttpRequest();
req.open("GET", "/authors", false);
req.send(null);
console.log(req.responseText);

// 使用GET請求查詢第四條book:/books/3
req = new XMLHttpRequest();
req.open("GET", "/books/3", false);
req.send(null);
console.log(req.responseText);

// 使用POST請求插入數據
req = new XMLHttpRequest();
req.open("POST", "/books", false);
var updateData = JSON.stringify({
    id: 4, author_id:1, title:'Emma'});
req.send(updateData);
console.log(req.responseText);

// 使用PUT請求更改數據
req = new XMLHttpRequest();
req.open("PUT", "/books/2", false);
var modifyData = JSON.stringify({
    title:'傲慢與偏見'});
req.send(modifyData);
console.log("修改:");
console.log(req.responseText);

// 使用GET請求查詢所有的books
req = new XMLHttpRequest();
req.open("GET", "/books", false);
req.send(null);
console.log("修改后:");
console.log(req.responseText);

// Delete數據
req = new XMLHttpRequest();
req.open("DELETE", "/books/4", false);
req.send(null);
console.log("刪除:");
console.log(req.responseText);

// 使用GET請求查詢所有的books
req = new XMLHttpRequest();
req.open("GET", "/books", false);
req.send(null);
console.log("刪除后:");
console.log(req.responseText);

創建含有mock server的代碼框架

index.html

隨著我們編寫的功能增多,項目文件包含的文件也越來越復雜。為了方便后面的學習,我打算創建一個起始的代碼框架。文件結構如下:

Project Files
Project Files

起始代碼應該能夠運行,并且在今后增加功能時,盡量少變更。我們先來看index.html:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />

<script src="service/FakeRest.min.js"></script>

<script src="../resources/sap-ui-core.js" id="sap-ui-bootstrap"
    data-sap-ui-libs="sap.m" data-sap-ui-preload="async"
    data-sap-ui-theme="sap_bluecrystal"
    data-sap-ui-xx-bindingSyntax="complex"
    data-sap-ui-resourceroots='{"stonewang.sapui5.demo": "./"}'>
    
</script>

<script>
    sap.ui.getCore().attachInit(function() {
        sap.ui.require([ 
                "sap/m/Shell",
                "sap/ui/core/ComponentContainer",
                "stonewang/sapui5/demo/Component",
                "sap/ui/thirdparty/sinon" 
        ], 
                
        function(Shell, ComponentContainer, Component) {

            jQuery.ajax({
                url : "service/suppliers.json",
                success : function(oData) {
                    initAppWithFakeRest(oData);
                },
                error : function() {
                    alert("Could not start server");
                }
            });

            var initAppWithFakeRest = function(oData) {
                // initialize fake REST server
                var restServer = new FakeRest.Server();
                restServer.init(oData);

                var server = sinon.fakeServer.create();
                server.xhr.useFilters = true;
                server.autoRespond = true;
                server.autoRespondAfter = 0;

                server.xhr.addFilter(function(method, url) {
                    //whenever the this returns true the request will not faked
                    return !url.match(/Suppliers/);
                });

                // use sinon.js to monkey-patch XmlHttpRequest
                server.respondWith(restServer.getHandler());

                // initialize the UI component
                new Shell({
                    app : new ComponentContainer({
                        height : "100%",
                        component : new Component({
                            id : "mvcAppComponent"
                        })
                    })
                }).placeAt("content");
            }
        });
    });
</script>

</head>
<body class="sapUiBody" role="application">
    <div id="content"></div>
</body>
</html>

代碼說明:

  • jQuery.ajax通過url參數加載文本文件,如果加載成功,執行initAppWithFakeRest,如果失敗,提示不能啟動服務器。
jQuery.ajax({
    url : "service/suppliers.json",
    success : function(oData) {
        initAppWithFakeRest(oData);
    },
    error : function() {
        alert("Could not start server");
    }
});
  • initAppWithFakeRest函數中,初始化fake server、sinon server、component conatiner和component:
var initAppWithFakeRest = function(oData) {
    // initialize fake REST server
    var restServer = new FakeRest.Server();
    restServer.init(oData);

    var server = sinon.fakeServer.create();
    server.xhr.useFilters = true;
    server.autoRespond = true;
    server.autoRespondAfter = 0;

    server.xhr.addFilter(function(method, url) {
        //whenever the this returns true the request will not faked
        return !url.match(/Suppliers/);
    });

    // use sinon.js to monkey-patch XmlHttpRequest
    server.respondWith(restServer.getHandler());

    // initialize the UI component
    new Shell({
        app : new ComponentContainer({
            height : "100%",
            component : new Component({
                id : "mvcAppComponent"
            })
        })
    }).placeAt("content");
}

Component.js

Component.js中,通過jQuery.ajax方法發起GET請求,請求成功則設置application model為oData。

sap.ui.define([
          "sap/ui/core/UIComponent",
          "sap/ui/model/resource/ResourceModel",
          "sap/ui/model/json/JSONModel",
          "stonewang/sapui5/demo/model/AppModel"
    ], 
      
    function (UIComponent, ResourceModel, JSONModel, AppModel) {
        "use strict";

        return UIComponent.extend("stonewang.sapui5.demo.Component", {
        
            metadata : {
                manifest: "json"
            },

            init : function () {
                // call the base component's init function
                UIComponent.prototype.init.apply(this, arguments);              
                
                 var oAppModel = new JSONModel("/Suppliers");           

                 // set application data
                jQuery.ajax({
                    type : "GET",
                    contentType : "application/json",
                    url : "/Suppliers",
                    dataType : "json",
                    success : function(oData) {
                        oAppModel.setData(oData);
                    },
                    error : function() {
                        jQuery.sap.log.debug(
                            "Something went wrong while retrieving the data");
                    }
                });             
                
                this.setModel(oAppModel);
                
                // create the views based on the url/hash
                this.getRouter().initialize();
            } // end of init function
        });
});

設置啟動時候進入notFound視圖

manifest.json中,設置pattern為空的時候,target為notFound,從而進入not found視圖,后面再修改:

"routes": [
    {
        "pattern": "",
        "name": "notFound",
        "target": "notFound"
    }

notFound視圖

<core:View xmlns:core="sap.ui.core" 
           xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m"
        xmlns:html="http://www.w3.org/1999/xhtml">
        
    <MessagePage
            title="{i18n>notFoundTitle}"
            text="{i18n>notFoundText}"
            icon="{sap-icon://document}"
            id="page">
    </MessagePage>

</core:View>

搭建本篇的框架代碼,作為后面使用模擬服務器進行增刪改查的基礎。

Source Code

23_zui5_mock_server_skeleton

參考

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容