root/trunk/common/Client.js

Revision 250, 6.3 kB (checked in by ydnar, 2 years ago)

support URLs with existing query strings

  • Property svn:keywords set to Id
Line 
1/*
2Client Library
3$Id$
4
5Copyright (c) 2005, Six Apart, Ltd.
6All rights reserved.
7
8Redistribution and use in source and binary forms, with or without
9modification, are permitted provided that the following conditions are
10met:
11
12    * Redistributions of source code must retain the above copyright
13notice, this list of conditions and the following disclaimer.
14
15    * Redistributions in binary form must reproduce the above
16copyright notice, this list of conditions and the following disclaimer
17in the documentation and/or other materials provided with the
18distribution.
19
20    * Neither the name of "Six Apart" nor the names of its
21contributors may be used to endorse or promote products derived from
22this software without specific prior written permission.
23
24THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
27A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
28OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
30LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
36*/
37
38
39/* core client object */
40
41Client = new Class( Observable, {
42    init: function( url, user, password ) {
43        arguments.callee.applySuper( this, arguments );
44        this.url = url;
45        this.user = user;
46        this.password = password;
47        this.baseId = "c" + Unique.id();
48        this.count = 0;
49    },
50   
51   
52    call: function( obj ) {
53        return this.request( obj );
54    },
55   
56   
57    request: function( obj ) {
58        obj.client = this;
59        return new this.constructor.Request( obj );
60    },
61   
62   
63    getUniqueId: function() {
64        return this.baseId + "r" + this.count++;
65    }
66} );
67
68
69/* request object */
70
71Client.Request = new Class( Observable, {
72    contentType: "text/javascript+json",
73   
74   
75    init: function( obj ) {
76        arguments.callee.applySuper( this, arguments );
77        this.state = "new";
78        this.client = obj.client;
79        this.method = obj.method || "default";
80        this.params = obj.params || [];
81        this.heap = obj.heap;
82        this.id = defined( this.heap )
83            ? this.client.getUniqueId()
84            : null;
85        this.asynchronous = this.heap ? true : false;
86       
87        this.request = {
88            id: this.id,
89            method: this.method,
90            params: this.params
91        };
92       
93        if( obj.delay ) {
94            this.timer = new Timer( this.start.bind( this ), obj.delay, 1 );
95        } else
96            this.start();
97    },
98   
99   
100    start: function() {
101        this.timer = null;
102        this.state = "started";
103       
104        this.transport = new XMLHttpRequest();
105        if( this.id != null )
106            this.transport.onreadystatechange = this.readyStateChange.bind( this );
107           
108        this.transport.open( "POST", this.client.url, this.asynchronous, this.client.user, this.client.password );
109        this.transport.setRequestHeader( "content-type", this.contentType );
110   
111        this.transport.send( Object.toJSON( this.request ) );
112    },
113   
114   
115    stop: function() {
116        this.state = "stopped";
117        this.heap = null;
118        this.client = null;
119       
120        if( this.timer )
121            this.timer.stop();
122        if( this.transport )
123            this.transport.abort();
124    },
125   
126   
127    readyStateChange: function() {
128        if( this.transport.readyState != 4 || this.state != "started" )
129            return;
130       
131        this.state = "finished";
132        this.response = {
133            id: this.id,
134            result: null,
135            error: null
136        };
137       
138        try {
139            if ( this.transport.responseText.charAt(0) == "{" ) {
140                try {
141                    //this.response = Object.fromJSON( this.transport.responseText );
142                    /*
143                    if ( ( /^(\s+|[{}\[\]:,]|"(\\["\\\/bfnrtu]|[^\x00-\x1f"\\]+)*"|-?\d+(\.\d*)?([Ee][+-]?\d+)?|null|true|false)+$/.test(
144                        this.transport.responseText
145                    ) ) )
146                    */
147                        this.response = eval( "(" + this.transport.responseText + ")" );
148                    /*
149                    else
150                        throw "response failed pre eval test";
151                    */
152                } catch( e ) {
153                    this.response.error = "error in eval/parse of responseText";
154                }
155            } else {
156                this.response.error = "Status: " + this.transport.status + " Error: Response not in JSON format";
157                log.error( this.transport.responseText.encodeHTML() );
158            }
159        } catch( e ) {
160            if ( e.message )
161                e = e.message;
162            this.response.error = e;
163        }
164        this.response.status = this.transport.status;
165       
166        if( this.heap && this.heap.callback ) {
167            if ( this.processCallbacks( this.heap.callback ) )
168                return;
169        }
170
171        this.heap = null;
172        this.client = null;
173    },
174
175   
176    processCallbacks: function( callbacks ) {
177        /* support 1 or more callbacks */
178        if ( callbacks instanceof Array ) {
179            for ( var i = 0; i < callbacks.length; i++ ) {
180                callbacks[ i ]( this.response, this.heap, this );
181            }
182        } else {
183            callbacks( this.response, this.heap, this );
184        }
185
186        return false;
187    },
188
189
190    pause: function() {
191        this.state = "paused";
192        if( this.timer )
193            this.timer.pause();
194    }
195
196} );
197
198
199Client.simpleRequest = function( url, params, callback ) {
200    url = url + (url.match( /\?/ ) ? "&" : "?") + String.encodeQuery( params );
201    var transport = new XMLHttpRequest();
202    transport.onreadystatechange = function() {
203        if( transport.readyState != 4 )
204            return;
205        callback( transport.responseText );
206    };
207    transport.open( "GET", url, true );
208    transport.send( "" );
209};
Note: See TracBrowser for help on using the browser.