3 // We allow people to omit these default parameters from API requests
4 // there is very customizable error handling here, on a per-call basis
5 // wondering, would it be simpler to make it easy to clone the api object,
6 // change error handling, and use that instead?
9 // Query parameters for API requests
15 // Ajax options for jQuery.ajax()
17 url
: mw
.util
.wikiScript( 'api' ),
19 timeout
: 30 * 1000, // 30 seconds
27 * Constructor to create an object to interact with the API of a particular MediaWiki server.
28 * mw.Api objects represent the API of a particular MediaWiki server.
30 * TODO: Share API objects with exact same config.
32 * var api = new mw.Api();
36 * } ).done ( function ( data ) {
37 * console.log( data );
43 * @param {Object} options See defaultOptions documentation above. Ajax options can also be
44 * overridden for each individual request to {@link jQuery#ajax} later on.
46 mw
.Api = function ( options
) {
48 if ( options
=== undefined ) {
52 // Force toString if we got a mw.Uri object
53 if ( options
.ajax
&& options
.ajax
.url
!== undefined ) {
54 options
.ajax
.url
= String( options
.ajax
.url
);
57 options
.parameters
= $.extend( {}, defaultOptions
.parameters
, options
.parameters
);
58 options
.ajax
= $.extend( {}, defaultOptions
.ajax
, options
.ajax
);
60 this.defaults
= options
;
66 * Normalize the ajax options for compatibility and/or convenience methods.
68 * @param {Object} [arg] An object contaning one or more of options.ajax.
69 * @return {Object} Normalized ajax options.
71 normalizeAjaxOptions: function ( arg
) {
72 // Arg argument is usually empty
73 // (before MW 1.20 it was used to pass ok callbacks)
75 // Options can also be a success callback handler
76 if ( typeof arg
=== 'function' ) {
83 * Perform API get request
85 * @param {Object} parameters
86 * @param {Object|Function} [ajaxOptions]
87 * @return {jQuery.Promise}
89 get: function ( parameters
, ajaxOptions
) {
90 ajaxOptions
= this.normalizeAjaxOptions( ajaxOptions
);
91 ajaxOptions
.type
= 'GET';
92 return this.ajax( parameters
, ajaxOptions
);
96 * Perform API post request
98 * TODO: Post actions for non-local hostnames will need proxy.
100 * @param {Object} parameters
101 * @param {Object|Function} [ajaxOptions]
102 * @return {jQuery.Promise}
104 post: function ( parameters
, ajaxOptions
) {
105 ajaxOptions
= this.normalizeAjaxOptions( ajaxOptions
);
106 ajaxOptions
.type
= 'POST';
107 return this.ajax( parameters
, ajaxOptions
);
111 * Perform the API call.
113 * @param {Object} parameters
114 * @param {Object} [ajaxOptions]
115 * @return {jQuery.Promise} Done: API response data and the jqXHR object.
118 ajax: function ( parameters
, ajaxOptions
) {
120 apiDeferred
= $.Deferred(),
123 parameters
= $.extend( {}, this.defaults
.parameters
, parameters
);
124 ajaxOptions
= $.extend( {}, this.defaults
.ajax
, ajaxOptions
);
126 // Ensure that token parameter is last (per [[mw:API:Edit#Token]]).
127 if ( parameters
.token
) {
128 token
= parameters
.token
;
129 delete parameters
.token
;
131 // Some deployed MediaWiki >= 1.17 forbid periods in URLs, due to an IE XSS bug
132 // So let's escape them here. See bug #28235
133 // This works because jQuery accepts data as a query string or as an Object
134 ajaxOptions
.data
= $.param( parameters
).replace( /\./g, '%2E' );
136 // If we extracted a token parameter, add it back in.
138 ajaxOptions
.data
+= '&token=' + encodeURIComponent( token
);
141 // Backwards compatibility: Before MediaWiki 1.20,
142 // callbacks were done with the 'ok' and 'err' property in ajaxOptions.
143 if ( ajaxOptions
.ok
) {
144 apiDeferred
.done( ajaxOptions
.ok
);
145 delete ajaxOptions
.ok
;
147 if ( ajaxOptions
.err
) {
148 apiDeferred
.fail( ajaxOptions
.err
);
149 delete ajaxOptions
.err
;
152 // Make the AJAX request
153 xhr
= $.ajax( ajaxOptions
)
154 // If AJAX fails, reject API call with error code 'http'
155 // and details in second argument.
156 .fail( function ( xhr
, textStatus
, exception
) {
157 apiDeferred
.reject( 'http', {
159 textStatus
: textStatus
,
163 // AJAX success just means "200 OK" response, also check API error codes
164 .done( function ( result
, textStatus
, jqXHR
) {
165 if ( result
=== undefined || result
=== null || result
=== '' ) {
166 apiDeferred
.reject( 'ok-but-empty',
167 'OK response but empty result (check HTTP headers?)'
169 } else if ( result
.error
) {
170 var code
= result
.error
.code
=== undefined ? 'unknown' : result
.error
.code
;
171 apiDeferred
.reject( code
, result
);
173 apiDeferred
.resolve( result
, jqXHR
);
177 // Return the Promise
178 return apiDeferred
.promise( { abort
: xhr
.abort
} ).fail( function ( code
, details
) {
179 mw
.log( 'mw.Api error: ', code
, details
);
184 * Post to API with specified type of token. If we have no token, get one and try to post.
185 * If we have a cached token try using that, and if it fails, blank out the
186 * cached token and start over. For example to change an user option you could do:
188 * new mw.Api().postWithToken( 'options', {
190 * optionname: 'gender',
191 * optionvalue: 'female'
194 * @param {string} tokenType The name of the token, like options or edit.
195 * @param {Object} params API parameters
196 * @return {jQuery.Promise} See #post
198 postWithToken: function ( tokenType
, params
) {
199 var api
= this, hasOwn
= tokenCache
.hasOwnProperty
;
200 if ( hasOwn
.call( tokenCache
, tokenType
) && tokenCache
[tokenType
] !== undefined ) {
201 params
.token
= tokenCache
[tokenType
];
202 return api
.post( params
).then(
205 if ( code
=== 'badtoken' ) {
206 // force a new token, clear any old one
207 tokenCache
[tokenType
] = params
.token
= undefined;
208 return api
.post( params
);
210 // Pass the promise forward, so the caller gets error codes
215 return api
.getToken( tokenType
).then( function ( token
) {
216 tokenCache
[tokenType
] = params
.token
= token
;
217 return api
.post( params
);
223 * Api helper to grab any token.
225 * @param {string} type Token type.
226 * @return {jQuery.Promise}
227 * @return {Function} return.done
228 * @return {string} return.done.token Received token.
230 getToken: function ( type
) {
234 apiPromise
= this.get( {
238 .done( function ( data
) {
239 // If token type is not available for this user,
240 // key '...token' is missing or can contain Boolean false
241 if ( data
.tokens
&& data
.tokens
[type
+ 'token'] ) {
242 d
.resolve( data
.tokens
[type
+ 'token'] );
244 d
.reject( 'token-missing', data
);
249 return d
.promise( { abort
: apiPromise
.abort
} );
256 * List of errors we might receive from the API.
257 * For now, this just documents our expectation that there should be similar messages
261 // occurs when POST aborted
262 // jQuery 1.4 can't distinguish abort or lost connection from 200 OK + empty result
268 // really a warning, but we treat it like an error
272 // upload succeeded, but no image info.
273 // this is probably impossible, but might as well check for it
275 // remote errors, defined in API
284 'copyuploaddisabled',
290 'filetype-banned-type',
293 'verification-error',
300 'fileexists-shared-forbidden',
308 * List of warnings we might receive from the API.
309 * For now, this just documents our expectation that there should be similar messages
317 }( mediaWiki
, jQuery
) );