source: Dev/branches/rest-dojo-ui/client/dojox/rpc/Rest.js @ 256

Last change on this file since 256 was 256, checked in by hendrikvanantwerpen, 13 years ago

Reworked project structure based on REST interaction and Dojo library. As
soon as this is stable, the old jQueryUI branch can be removed (it's
kept for reference).

File size: 5.2 KB
Line 
1define("dojox/rpc/Rest", ["dojo", "dojox"], function(dojo, dojox) {
2// Note: This doesn't require dojox.rpc.Service, and if you want it you must require it
3// yourself, and you must load it prior to dojox.rpc.Rest.
4
5// summary:
6//              This provides a HTTP REST service with full range REST verbs include PUT,POST, and DELETE.
7// description:
8//              A normal GET query is done by using the service directly:
9//              | var restService = dojox.rpc.Rest("Project");
10//              | restService("4");
11//              This will do a GET for the URL "/Project/4".
12//              | restService.put("4","new content");
13//              This will do a PUT to the URL "/Project/4" with the content of "new content".
14//              You can also use the SMD service to generate a REST service:
15//              | var services = dojox.rpc.Service({services: {myRestService: {transport: "REST",...
16//              | services.myRestService("parameters");
17//
18//              The modifying methods can be called as sub-methods of the rest service method like:
19//      | services.myRestService.put("parameters","data to put in resource");
20//      | services.myRestService.post("parameters","data to post to the resource");
21//      | services.myRestService['delete']("parameters");
22
23  dojo.getObject("rpc.Rest", true, dojox);
24
25        if(dojox.rpc && dojox.rpc.transportRegistry){
26                // register it as an RPC service if the registry is available
27                dojox.rpc.transportRegistry.register(
28                        "REST",
29                        function(str){return str == "REST";},
30                        {
31                                getExecutor : function(func,method,svc){
32                                        return new dojox.rpc.Rest(
33                                                method.name,
34                                                (method.contentType||svc._smd.contentType||"").match(/json|javascript/), // isJson
35                                                null,
36                                                function(id, args){
37                                                        var request = svc._getRequest(method,[id]);
38                                                        request.url= request.target + (request.data ? '?'+  request.data : '');
39                                                        if(args && (args.start >= 0 || args.count >= 0)){
40                                                                request.headers = request.headers || {};
41                                                                request.headers.Range = "items=" + (args.start || '0') + '-' +
42                                                                        (("count" in args && args.count != Infinity) ?
43                                                                                (args.count + (args.start || 0) - 1) : '');
44                                                        }
45                                                        return request;
46                                                }
47                                        );
48                                }
49                        }
50                );
51        }
52        var drr;
53
54        function index(deferred, service, range, id){
55                deferred.addCallback(function(result){
56                        if(deferred.ioArgs.xhr && range){
57                                        // try to record the total number of items from the range header
58                                        range = deferred.ioArgs.xhr.getResponseHeader("Content-Range");
59                                        deferred.fullLength = range && (range=range.match(/\/(.*)/)) && parseInt(range[1]);
60                        }
61                        return result;
62                });
63                return deferred;
64        }
65        drr = dojox.rpc.Rest = function(/*String*/path, /*Boolean?*/isJson, /*Object?*/schema, /*Function?*/getRequest){
66                // summary:
67                //              Creates a REST service using the provided path.
68                var service;
69                // it should be in the form /Table/
70                service = function(id, args){
71                        return drr._get(service, id, args);
72                };
73                service.isJson = isJson;
74                service._schema = schema;
75                // cache:
76                //              This is an object that provides indexing service
77                //              This can be overriden to take advantage of more complex referencing/indexing
78                //              schemes
79                service.cache = {
80                        serialize: isJson ? ((dojox.json && dojox.json.ref) || dojo).toJson : function(result){
81                                return result;
82                        }
83                };
84                // the default XHR args creator:
85                service._getRequest = getRequest || function(id, args){
86                        if(dojo.isObject(id)){
87                                id = dojo.objectToQuery(id);
88                                id = id ? "?" + id: "";
89                        }
90                        if(args && args.sort && !args.queryStr){
91                                id += (id ? "&" : "?") + "sort("
92                                for(var i = 0; i<args.sort.length; i++){
93                                        var sort = args.sort[i];
94                                        id += (i > 0 ? "," : "") + (sort.descending ? '-' : '+') + encodeURIComponent(sort.attribute);
95                                }
96                                id += ")";
97                        }
98                        var request = {
99                                url: path + (id == null ? "" : id),
100                                handleAs: isJson ? 'json' : 'text',
101                                contentType: isJson ? 'application/json' : 'text/plain',
102                                sync: dojox.rpc._sync,
103                                headers: {
104                                        Accept: isJson ? 'application/json,application/javascript' : '*/*'
105                                }
106                        };
107                        if(args && (args.start >= 0 || args.count >= 0)){
108                                request.headers.Range = "items=" + (args.start || '0') + '-' +
109                                        (("count" in args && args.count != Infinity) ?
110                                                (args.count + (args.start || 0) - 1) : '');
111                        }
112                        dojox.rpc._sync = false;
113                        return request;
114                };
115                // each calls the event handler
116                function makeRest(name){
117                        service[name] = function(id,content){
118                                return drr._change(name,service,id,content); // the last parameter is to let the OfflineRest know where to store the item
119                        };
120                }
121                makeRest('put');
122                makeRest('post');
123                makeRest('delete');
124                // record the REST services for later lookup
125                service.servicePath = path;
126                return service;
127        };
128
129        drr._index={};// the map of all indexed objects that have gone through REST processing
130        drr._timeStamps={};
131        // these do the actual requests
132        drr._change = function(method,service,id,content){
133                // this is called to actually do the put, post, and delete
134                var request = service._getRequest(id);
135                request[method+"Data"] = content;
136                return index(dojo.xhr(method.toUpperCase(),request,true),service);
137        };
138
139        drr._get= function(service,id, args){
140                args = args || {};
141                // this is called to actually do the get
142                return index(dojo.xhrGet(service._getRequest(id, args)), service, (args.start >= 0 || args.count >= 0), id);
143        };
144
145        return dojox.rpc.Rest;
146});
Note: See TracBrowser for help on using the repository browser.