SAPUI5 (23)

来源:互联网 发布:cad绘图软件 编辑:程序博客网 时间:2024/06/10 05:14

模拟服务器(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>
  • 2) 将mockServerTest.html文件放在webapp下的test文件夹下。用于测试代码。

  • 3) 加载sinon模块

jQuery.sap.require("sap.ui.thirdparty.sinon");
  • 4) 加载数据并初始化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 servervar restServer = new FakeRest.Server();restServer.init(data);// use sinon.js to monkey-patch XmlHttpRequestvar server = sinon.fakeServer.create();server.respondWith(restServer.getHandler());
  • 5) 在mock server中实现增删改查操作
// 使用GET请求查询所有的authorvar req = new XMLHttpRequest();req.open("GET", "/authors", false);req.send(null);console.log(req.responseText);// 使用GET请求查询第四条book:/books/3req = 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请求查询所有的booksreq = 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请求查询所有的booksreq = new XMLHttpRequest();req.open("GET", "/books", false);req.send(null);console.log("删除后:");console.log(req.responseText);

创建含有mock server的代码框架

index.html

随着我们编写的功能增多,项目文件包含的文件也越来越复杂。为了方便后面的学习,我打算创建一个起始的代码框架。文件结构如下:

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

参考

  • FakeRest
0 0
原创粉丝点击