Add SPARQL client to core
[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 !!data.query.pages[ 0 ].categoryinfo;
25 } )
26 .promise( { abort: apiPromise.abort } );
27 },
28
29 /**
30 * Get a list of categories that match a certain prefix.
31 *
32 * E.g. given "Foo", return "Food", "Foolish people", "Foosball tables"...
33 *
34 * @param {string} prefix Prefix to match.
35 * @return {jQuery.Promise}
36 * @return {Function} return.done
37 * @return {string[]} return.done.categories Matched categories
38 */
39 getCategoriesByPrefix: function ( prefix ) {
40 // Fetch with allpages to only get categories that have a corresponding description page.
41 var apiPromise = this.get( {
42 formatversion: 2,
43 list: 'allpages',
44 apprefix: prefix,
45 apnamespace: mw.config.get( 'wgNamespaceIds' ).category
46 } );
47
48 return apiPromise
49 .then( function ( data ) {
50 return data.query.allpages.map( function ( category ) {
51 return new mw.Title( category.title ).getMainText();
52 } );
53 } )
54 .promise( { abort: apiPromise.abort } );
55 },
56
57 /**
58 * Get the categories that a particular page on the wiki belongs to.
59 *
60 * @param {mw.Title|string} title
61 * @return {jQuery.Promise}
62 * @return {Function} return.done
63 * @return {boolean|mw.Title[]} return.done.categories List of category titles or false
64 * if title was not found.
65 */
66 getCategories: function ( title ) {
67 var apiPromise = this.get( {
68 formatversion: 2,
69 prop: 'categories',
70 titles: String( title )
71 } );
72
73 return apiPromise
74 .then( function ( data ) {
75 var page = data.query.pages[ 0 ];
76
77 if ( !page.categories ) {
78 return false;
79 }
80 return page.categories.map( function ( cat ) {
81 return new mw.Title( cat.title );
82 } );
83 } )
84 .promise( { abort: apiPromise.abort } );
85 }
86 } );
87
88 /**
89 * @class mw.Api
90 * @mixins mw.Api.plugin.category
91 */
92
93 }( mediaWiki, jQuery ) );