jsonRest与dojo的复杂结构

时间:2011-11-10 01:15:28

标签: javascript rest dojo

我正在开发一个基于dojo框架的Web应用程序。

我决定使用dojox.data.JsonRestStore与服务器进行通信。

例如,我在Json中有这种Order(电子商务)的表示形式:

{
id: int,
name: str,
date: str,
items: [
    {
        id: int,
        name: str,
        pcs: int,
        price: int,
        total: int

    }, ...
]
}

Order有一些基本属性(id,name,date),它还包含有序项的数组。

我不确定这是否是好的(REST)设计,我想知道订购的项目是否应该在一个单独的资源中(因此在单独的jsonRestStore中)。

我想当我想在dojo Form中显示Orders的基本属性和在dojo Datagrid中显示有序项时,我可能会遇到当前对象模型的问题。

所以我的问题是,我目前的做法是否正确 - 在创建REST客户端应用程序方面?另外,在dojo中使用datagrid实现我的示例表单的正确方法是什么?

2 个答案:

答案 0 :(得分:3)

虽然您的设计是RESTful并且REST架构中没有任何内容需要它,但我认为大多数人会同意保持资源分离是最好的方法。如果您查看Restful Web Services,他们会将此描述为资源导向架构。

我已经找到了一个示例,它将订单和项目保存在单独的JsonRestStores中,并允许您通过Dojo表单显示Order对象,并通过Dojo DataGrid显示订单的项目。我认为代码很简单,我还在代码中添加了一些注释以尝试清理。

我创建了一个简单的ASP.NET MVC 3后端,为示例提供了一些虚拟数据。我也发布了该代码,虽然您真的只对代码的“视图”部分感兴趣,但后端代码也可以帮助您找出或更改您拥有的任何后端代码。

查看:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <title>JsonRestStore Datagrid Example</title>

<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/resources/dojo.css"/>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dijit/themes/tundra/tundra.css"/>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojox/grid/resources/Grid.css"/>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojox/grid/resources/tundraGrid.css"/>

<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/dojo.xd.js' djConfig="parseOnLoad:true"></script>

<script type="text/javascript">

    dojo.require("dojox.data.JsonRestStore");
    dojo.require("dojox.grid.DataGrid");
    dojo.require("dijit.form.DateTextBox");
    dojo.require("dojox.grid.cells.dijit");
    dojo.require("dojo.date.locale");
    var item_structure = null;

    dojo.ready(function () {
        setItemTableStructure();
        //retrieve a single order
        //expects json to look like
        // {"Id":2,"Name":"Order Name 2","Date":"\/Date(1321135185260)\/","Items":{"Ref":"/Order/2/Items"}}
        order_store = new dojox.data.JsonRestStore({ target: "/Order/2", idAttribute: "Id" });

        order_store.fetch({
            onComplete: function (item) {
                //this method is called after an item is fetched into the store
                //item here is the order json object
                var orderId = new dijit.form.TextBox({ value: order_store.getValue(item, 'Id') }, 'orderId');
                var orderName = new dijit.form.TextBox({ value: order_store.getValue(item, 'Name') }, 'orderName');
                var orderDate = new dijit.form.DateTextBox({ value: parseJsonDate(order_store.getValue(item, 'Date')) }, 'orderDate');
                var items = order_store.getValue(item, 'Items').Ref;

                //make a call to retrieve the items that are contained within a particular order
                //expects a json object that looks like
                //[{"Ref":"/Item/1"},{"Ref":"/Item/2"},{"Ref":"/Item/3"},{"Ref":"/Item/4"},{"Ref":"/Item/5"}]
                var xhrArgs = {
                    url: items,
                    handleAs: "json",
                    load: loadOrder, //main method
                    error: function (error) {
                        console.log(error);
                    }
                }
                var deferred = dojo.xhrGet(xhrArgs);
            }
        });
    });

    //This is the main method
    function loadOrder(data) {
        var itemIds = "";
        dojo.forEach(data, function(item, i){
            itemIds += item.Ref.charAt(item.Ref.length-1);
            itemIds += ",";
        });
        itemIds = itemIds.substring(0, itemIds.length-1);

        //build the backend to accept a comma seperated list of item ids
        //like    /Item/1,2,3
        item_store = new dojox.data.JsonRestStore({target:"/Item/" + itemIds, idAttribute:"Id"});
        items = new dojox.grid.DataGrid({
            name: "items",
            formatter: function(date) {
                        if (date) return dojo.date.locale.format(parseJsonDate(date), {
                            selector: "Date"
                        })
                    },
            structure: item_structure,
            store: item_store
        }, dojo.byId('orderItems'));

        items.startup();
    }

    function setItemTableStructure() {
        item_structure = [
        { 
          field: 'Id'
        },
        {
          field: 'Name'
        },
        {
          field: 'Price'
        },
        {
            field: 'Date',
            type: dojox.grid.cells.DateTextBox,
            widgetProps: {
                selector: "Date"
            },
            formatter: function(v) {
                if (v) return dojo.date.locale.format(parseJsonDate(v), {
                    selector: 'Date'
                })
            }
        }];
    }

    function parseJsonDate(jsonDate) {
        var offset = new Date().getTimezoneOffset() * 60000;
        var parts = /\/Date\((-?\d+)([+-]\d{2})?(\d{2})?.*/.exec(jsonDate);

        if (parts[2] == undefined)
          parts[2] = 0;

        if (parts[3] == undefined)
          parts[3] = 0;

        return new Date(+parts[1] + offset + parts[2]*3600000 + parts[3]*60000);
    }
  </script>
  </head>
  <body>
    <h1>Json Rest Store with DataGrid Example</h1><br />

    <form style='margin: 10px' action='post'>
    <h2>Order</h2>
    <input id='orderId' />
    <input id='orderName' />
    <input id='orderDate' />
    </form>
    <h2>Items</h2>
    <div id='orderItems'></div>
    </body>
 </html>

型号:

using System;

namespace OrdersRestService.Models
{
    public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public double Price { get; set; }
        public DateTime Date { get; set; }
    }
}

public class Order
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime Date { get; set; }
    public Reference Items { get; set; }
}

public class Reference
{
    public string Ref { get; set; }
}

控制器:

namespace OrdersRestService.Controllers
{
    public class OrderController : Controller
    {
        public ActionResult Index(string id)
        {
            Order order = new Order
                              {
                                  Id = Convert.ToInt32(id),
                                  Name = "Order Name " + id,
                                  Date = DateTime.Now,
                                  Items = new Reference
                                                {
                                                    Ref = "/Order/" + id + "/Items"
                                                }
                              };

            return Json(order, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Items()
        {
            List<Reference> items = new List<Reference>();

            for (int i = 1; i <= 5; i++)
            {
                Reference r = new Reference();
                r.Ref = "/Item/" + i;
                items.Add(r);
            }

            return Json(items, JsonRequestBehavior.AllowGet);
        }
    }

    public class ItemController : Controller
    {
        public ActionResult Index(string id)
        {
            List<Item> items = new List<Item>();
            foreach (string itemid in id.Split(','))
            {
                Item item = new Item 
                                  {
                                      Id = Convert.ToInt32(itemid),
                                      Name = "Item Name " + itemid,
                                      Date = DateTime.Now,
                                  };
                items.Add(item);
            }

            return Json(items, JsonRequestBehavior.AllowGet);
        }
    }

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

Global.aspx.cs

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "DefaultWithAction", // Route name
            "{controller}/{id}/{action}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }
}

答案 1 :(得分:1)

你的方法很好。无论是在关系数据库还是平面文本文件中,REST客户端都不需要知道数据的存储方式。您绝对可以在过帐到订单端点时包含订单商品。此设计更快,服务器请求更少。而不是发布一次创建订单,等待订单ID,然后发布所有项目,而不是发布一次。

REST是关于使用现有的HTTP谓词(如POST,DELETE,GET,PUT等)来简化端点。我们的想法是使用HTTP协议作为应用程序界面的一部分。它没有规定你的模型应该如何设计。