Merge "Add tablesUsed to RevisionStoreDbTest"
[lhc/web/wiklou.git] / resources / src / mediawiki / api / category.js
1 /**
2 * @class mw.Api.plugin.category
3 */
4 ( function ( mw, $ ) {
5
6 $.extend( mw.Api.prototype, {
7 /**
8 * Determine if a category exists.
9 *
10 * @param {mw.Title|string} title
11 * @return {jQuery.Promise}
12 * @return {Function} return.done
13 * @return {boolean} return.done.isCategory Whether the category exists.
14 */
15 isCategory: function ( title ) {
16 var apiPromise = this.get( {
17 formatversion: 2,
18 prop: 'categoryinfo',
19 titles: [ String( title ) ]
20 } );
21
22 return apiPromise
23 .then( function ( data ) {
24 return !!(
25 data.query && // query is missing on title=""
26 data.query.pages && // query.pages is missing on title="#" or title="mw:"
27 data.query.pages[ 0 ].categoryinfo
28 );
29 } )
30 .promise( { abort: apiPromise.abort } );
31 },
32
33 /**
34 * Get a list of categories that match a certain prefix.
35 *
36 * E.g. given "Foo", return "Food", "Foolish people", "Foosball tables"...
37 *
38 * @param {string} prefix Prefix to match.
39 * @return {jQuery.Promise}
40 * @return {Function} return.done
41 * @return {string[]} return.done.categories Matched categories
42 */
43 getCategoriesByPrefix: function ( prefix ) {
44 // Fetch with allpages to only get categories that have a corresponding description page.
45 var apiPromise = this.get( {
46 formatversion: 2,
47 list: 'allpages',
48 apprefix: prefix,
49 apnamespace: mw.config.get( 'wgNamespaceIds' ).category
50 } );
51
52 return apiPromise
53 .then( function ( data ) {
54 return data.query.allpages.map( function ( category ) {
55 return new mw.Title( category.title ).getMainText();
56 } );
57 } )
58 .promise( { abort: apiPromise.abort } );
59 },
60
61 /**
62 * Get the categories that a particular page on the wiki belongs to.
63 *
64 * @param {mw.Title|string} title
65 * @return {jQuery.Promise}
66 * @return {Function} return.done
67 * @return {boolean|mw.Title[]} return.done.categories List of category titles or false
68 * if title was not found.
69 */
70 getCategories: function ( title ) {
71 var apiPromise = this.get( {
72 formatversion: 2,
73 prop: 'categories',
74 titles: [ String( title ) ]
75 } );
76
77 return apiPromise
78 .then( function ( data ) {
79 var page;
80
81 if ( !data.query || !data.query.pages ) {
82 return false;
83 }
84 page = data.query.pages[ 0 ];
85 if ( !page.categories ) {
86 return false;
87 }
88 return page.categories.map( function ( cat ) {
89 return new mw.Title( cat.title );
90 } );
91 } )
92 .promise( { abort: apiPromise.abort } );
93 }
94 } );
95
96 /**
97 * @class mw.Api
98 * @mixins mw.Api.plugin.category
99 */
100
101 }( mediaWiki, jQuery ) );