User:Erutuon/scripts/apiWrapper.js

mw.loader.using("mediawiki.api", function apiWrapperInnards { "use strict";

var apiWrapper = Object.create(null); window.apiWrapper = apiWrapper;

function check(wikitext, callback) { if (typeof wikitext !== "string") throw new TypeError("Expected string"); if (typeof callback !== "function") throw new TypeError("Expected function"); }

apiWrapper.parse = function (wikitext, callback, pageName) { check(wikitext, callback); return new mw.Api.get({		action: "parse",		text: wikitext,		prop: "text",		title: pageName || mw.config.get("wgPageName"),	}).done(function (data) {		var text = data.parse.text["*"];		// Remove parsing information.		text = text.replace( /^([^\0]+)\n\n<\/div>$/, "$1");		callback(text);	}); };

apiWrapper.expandTemplates = function (wikitext, callback, pageName) { check(wikitext, callback); return new mw.Api.get({		action: "expandtemplates",		title: pageName || mw.config.get("wgPageName"),		text: wikitext,		prop: "wikitext",	}).done(function (data) {		var expanded = data.expandtemplates.wikitext;		callback(expanded);	}); };

apiWrapper.getWikitext = function (pageName, callback) { check(pageName, callback); return new mw.Api.get({		action: "query",		prop: "revisions",		rvprop: "content",		titles: pageName,		rvlimit: 1,		rvslots: "*",	}).done(function (data) {		var pages = data.query.pages;		if (pages[-1])			throw new Error("Page not found"); // maybe?		for (var pageId in pages) {			// Why so complicated?			var wikitext = pages[pageId].revisions[0].slots.main["*"];			callback(wikitext);		}	}); };

// See also w:MediaWiki:Gadget-libLua.js. apiWrapper.callLua = function (expression, callback) { check(expression, callback); return new mw.Api.postWithToken('csrf', {		action: 'scribunto-console',		format:'json',		title: 'Example',		content: '',		question: '= ' + expression,		clear: true	}).then(function (data) { // This is much more complicated.		if (data.type === "error")			throw new Error(data.message);		callback(data.return);	}); };

// new mw.Api.get({ action: 'query', meta: 'siteinfo', siprop: 'interwikimap', format: 'json' }).done(data => window.interwiki = data.query.interwikimap)

});