Nuria has submitted this change and it was merged.
Change subject: Implement mediawiki-storage lib
......................................................................
Implement mediawiki-storage lib
This library is intended to permit Dashiki and other projects
to get json content from mediawiki pages. To avoid cross origin
problems, mediawiki-storage uses jsonp. It is put together as
a bower package, it uses karma for testing and gulp for building.
Bug: 68448
Change-Id: I8f94f9f5df7f2146e25b1d08a21d77b91a59f9d1
---
A .bowerrc
A .gitignore
A .gitreview
A .jshintrc
A LICENSE
A README.md
A bower.json
A dist/mediawiki-storage.js
A dist/mediawiki-storage.min.js
A doc/api.md
A gulpfile.js
A karma.conf.js
A package.json
A src/mediawiki-storage.js
A test/mediawiki-storage-spec.js
15 files changed, 904 insertions(+), 0 deletions(-)
Approvals:
Nuria: Verified; Looks good to me, approved
diff --git a/.bowerrc b/.bowerrc
new file mode 100644
index 0000000..b418e31
--- /dev/null
+++ b/.bowerrc
@@ -0,0 +1,3 @@
+{
+ "directory": "src/bower_modules"
+}
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..dc84f25
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+/src/bower_modules
+/node_modules
diff --git a/.gitreview b/.gitreview
new file mode 100644
index 0000000..27d66ac
--- /dev/null
+++ b/.gitreview
@@ -0,0 +1,6 @@
+[gerrit]
+host=gerrit.wikimedia.org
+port=29418
+project=analytics/mediawiki-storage.git
+defaultbranch=master
+defaultrebase=0
diff --git a/.jshintrc b/.jshintrc
new file mode 100644
index 0000000..7788cef
--- /dev/null
+++ b/.jshintrc
@@ -0,0 +1,20 @@
+// Example: https://github.com/jshint/jshint/blob/master/examples/.jshintrc
+// Documentation: http://www.jshint.com/docs/
+{
+ "browser": true,
+ "globalstrict": true,
+ "undef": true,
+ "node": true,
+ "validthis": true,
+ "jquery": true,
+
+ "globals": {
+ "describe": true,
+ "it": true,
+ "expect": true,
+ "require": true,
+ "define": true,
+ "mediawikiStorage": true,
+ "sinon": true
+ }
+}
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..6d525ef
--- /dev/null
+++ b/README.md
@@ -0,0 +1,45 @@
+# mediawiki-storage
+
+Get JSON content from MediaWiki using JSONP
+
+### Use as a Bower component
+Install normally with Bower.
+```
+bower install --save mediawiki-storage
+```
+
+### Use to modify and develop
+Get the source code from Wikimedia's Gerrit repository.
+```
+git clone https://gerrit.wikimedia.org/r/analytics/mediawiki-storage
+```
+
+We're using Bower for production dependencies, Karma as a test runner and Gulp
as a build tool. Make sure you install the following packages globally.
+```
+npm install -g bower
+npm install -g gulp
+npm install -g karma-cli
+```
+
+Then, install the dependencies to be able to build and run mediawiki-storage
and its tests.
+```
+cd mediawiki-storage
+npm install
+bower install
+```
+
+Now you can run Gulp tasks to lint, build and clean the project; Where
_command_ can be one of: `lint`, `build` or `clean`. If you omit _command_,
Gulp defaults to executing _build_ task.
+```
+gulp <command>
+```
+
+You can also run the tests, and let Karma test runner watch all files and
execute all tests on changes with:
+```
+karma start
+```
+
+### API documentation
+See the API documentation [here](doc/api.md).
+
+### Future plans
+In the future, we'd like to add write capability to the library, so that we
can also update the contents of MediaWiki JSON pages.
diff --git a/bower.json b/bower.json
new file mode 100644
index 0000000..85aa395
--- /dev/null
+++ b/bower.json
@@ -0,0 +1,32 @@
+{
+ "name": "mediawiki-storage",
+ "version": "0.0.0",
+ "authors": [
+ "Marcel Ruiz Forns <[email protected]>"
+ ],
+ "description": "Get JSON content from MediaWiki using JSONP",
+ "main": "src/mediawiki-storage.js",
+ "keywords": [
+ "mediawiki",
+ "storage",
+ "json",
+ "jsonp"
+ ],
+ "license": "Apache License 2.0",
+ "homepage": "https://github.com/wikimedia/analytics-mediawiki-storage",
+ "ignore": [
+ "dist",
+ ".git",
+ ".gitignore",
+ ".gitreview",
+ "gulpfile.js",
+ ".jshintrc",
+ "karma.conf.js",
+ "node_modules",
+ "package.json",
+ "test"
+ ],
+ "dependencies": {
+ "jquery": "~2.1.1"
+ }
+}
diff --git a/dist/mediawiki-storage.js b/dist/mediawiki-storage.js
new file mode 100644
index 0000000..70c2e42
--- /dev/null
+++ b/dist/mediawiki-storage.js
@@ -0,0 +1,145 @@
+'use strict';
+
+(function(global){
+
+ var MediawikiStorage = function () {};
+
+ /**
+ * Returns the contents of the specified mediawiki page
+ *
+ * The mediawiki page is specified using mediawiki's host
+ * (i.e. www.wikipedia.org) and either:
+ * - the page name
+ * - the page id
+ * - the revision id
+ *
+ * Note that:
+ * The page contents must be valid json.
+ * The retrieval of the page contents is done via jsonp.
+ * The return value is passed as parameter for the success callback.
+ * Errors occurring before jsonp call (TypeError) will be thrown
+ * synchronously, and errors occurring within or after jsonp call
+ * will be handed as parameter for error callback.
+ *
+ * Parameter: options {object}
+ * {
+ * host: {string}, // i.e. www.wikipedia.org
+ * // at least one of the following three:
+ * pageName: {string},
+ * pageId: {string},
+ * revId: {string},
+ * success: {function}, // callback [optional]
+ * // parameter: object with page contents
+ * error: {function} // callback [optional]
+ * // parameter: error thrown
+ * }
+ */
+ MediawikiStorage.prototype.get = function (options) {
+ if (typeof options !== 'object') {
+ throw new TypeError('function must receive an object');
+ }
+
+ var url = this._createQueryUrl(options);
+ var that = this;
+
+ $.ajax({
+ url: url,
+ dataType: 'jsonp',
+ contentType: 'application/json',
+
+ success: function (data) {
+ if (typeof options.success === 'function') {
+ var pageJson;
+ try {
+ pageJson = that._getPageJson(data);
+ } catch (e) {
+ return options.error(e);
+ }
+ options.success(pageJson);
+ }
+ },
+
+ error: function (jqXHR, textStatus, errorThrown) {
+ if (typeof options.error === 'function') {
+ options.error(errorThrown);
+ }
+ }
+ });
+ };
+
+ /**
+ * Given a host and a page identifier, creates
+ * a url for querying mediawiki's api for that page
+ */
+ MediawikiStorage.prototype._createQueryUrl = function (options) {
+ if (typeof options.host !== 'string') {
+ throw new TypeError('host must be a string');
+ }
+
+ // mediawiki api can be queried using three types of ids
+ // page names, page ids and revision ids
+ var filter;
+ if (typeof options.pageName === 'string') {
+ filter = '&titles=' + options.pageName;
+ } else if (typeof options.pageId === 'string') {
+ filter = '&pageids=' + options.pageId;
+ } else if (typeof options.revId === 'string') {
+ filter = '&revids=' + options.revId;
+ } else {
+ throw new TypeError(
+ 'one of (pageName|pageId|revId) must be a string'
+ );
+ }
+
+ // for reference, have a look at:
+ // http://www.mediawiki.org/wiki/API:Query
+ return [
+ 'http://',
+ options.host,
+ '/w/api.php',
+ '?action=query',
+ '&prop=revisions',
+ '&format=json',
+ '&rvprop=content',
+ filter
+ ].join('');
+ };
+
+ /**
+ * Given the result of mediawiki api query on a json formatted page
+ * extracts the contents of the page and parses them into an object
+ */
+ MediawikiStorage.prototype._getPageJson = function (data) {
+ var pageContent, result;
+
+ try {
+ var pages = data.query.pages;
+ var pageId = Object.keys(pages)[0];
+ pageContent = pages[pageId].revisions[0]['*'];
+ } catch (e) {
+ throw new SyntaxError('unexpected query result');
+ }
+
+ try {
+ result = JSON.parse(pageContent);
+ } catch (e) {
+ throw new SyntaxError('page contents are not a valid json');
+ }
+
+ return result;
+ };
+
+ var mediawikiStorage = new MediawikiStorage();
+
+ // exports to multiple environments
+ if(typeof define === 'function' && define.amd){ // AMD
+ define(function () { return mediawikiStorage; });
+ } else if (typeof module !== 'undefined' && module.exports){ // node
+ module.exports = mediawikiStorage;
+ } else { // browser
+ // use string because of Google closure compiler ADVANCED_MODE
+ /* jslint sub:true */
+ global['mediawikiStorage'] = mediawikiStorage;
+ }
+
+}(window));
diff --git a/dist/mediawiki-storage.min.js b/dist/mediawiki-storage.min.js
new file mode 100644
index 0000000..bfb3a4e
--- /dev/null
+++ b/dist/mediawiki-storage.min.js
@@ -0,0 +1 @@
+"use strict";!function(e){var
t=function(){};t.prototype.get=function(e){if("object"!=typeof e)throw new
TypeError("function must receive an object");var
t=this._createQueryUrl(e),r=this;$.ajax({url:t,dataType:"jsonp",contentType:"application/json",success:function(t){if("function"==typeof
e.success){var o;try{o=r._getPageJson(t)}catch(n){return
e.error(n)}e.success(o)}},error:function(t,r,o){"function"==typeof
e.error&&e.error(o)}})},t.prototype._createQueryUrl=function(e){if("string"!=typeof
e.host)throw new TypeError("host must be a string");var t;if("string"==typeof
e.pageName)t="&titles="+e.pageName;else if("string"==typeof
e.pageId)t="&pageids="+e.pageId;else{if("string"!=typeof e.revId)throw new
TypeError("one of (pageName|pageId|revId) must be a
string");t="&revids="+e.revId}return["http://",e.host,"/w/api.php","?action=query","&prop=revisions","&format=json","&rvprop=content",t].join("")},t.prototype._getPageJson=function(e){var
t,r;try{var
o=e.query.pages,n=Object.keys(o)[0];t=o[n].revisions[0]["*"]}catch(i){throw new
SyntaxError("unexpected query result")}try{r=JSON.parse(t)}catch(i){throw new
SyntaxError("page contents are not a valid json")}return r};var r=new
t;"function"==typeof define&&define.amd?define(function(){return
r}):"undefined"!=typeof
module&&module.exports?module.exports=r:e.mediawikiStorage=r}(window);
\ No newline at end of file
diff --git a/doc/api.md b/doc/api.md
new file mode 100644
index 0000000..5f23489
--- /dev/null
+++ b/doc/api.md
@@ -0,0 +1,53 @@
+# API Documentation
+
+mediawiki-storage should run within the following export environments: AMD
(define), Node.js (require) and browser (global). After you get
mediawiki-storage object, you can call the following methods on it:
+
+### get
+__Returns the contents of the specified mediawiki page.__
+
+The mediawiki page is specified using mediawiki's `host` and one of:
+
+* `pageName`
+* `pageId`
+* `revId`
+
+_Note that the page contents must be valid json._
+
+##### Parameters:
+
+1. options _{object}_ Dictionary with all options
+
+```
+{
+ host: {string},
+ pageName: {string},
+ pageId: {string},
+ revId: {string},
+ success: {function},
+ error: {function}
+}
+```
+
+##### Return value:
+
+Is passed as a single parameter to `success` callback.
+
+##### Errors thrown:
+
+Errors occurring before jsonp call will be thrown synchronously.
+If an error occures within or after the jsonp call, it will be passed to the
`error` callback as a single parameter, and execution will be aborted.
+
+##### Example:
+
+```
+mediawiki-storage.get({
+ host: 'meta.wikimedia.org',
+ pageName: 'Schema:EventCapsule',
+ success: function (data) {
+ console.log('Page contents:', data);
+ },
+ error: function (error) {
+ console.log('Error:', error);
+ }
+});
+```
diff --git a/gulpfile.js b/gulpfile.js
new file mode 100644
index 0000000..49fe28c
--- /dev/null
+++ b/gulpfile.js
@@ -0,0 +1,30 @@
+var gulp = require('gulp');
+var jshint = require('gulp-jshint');
+var del = require('del');
+var uglify = require('gulp-uglify');
+var rename = require('gulp-rename');
+
+// gulp lint: passes lint check on src/ and test/ js files
+var filesToLint = ['src/*.js', 'test/*.js'];
+gulp.task('lint', function() {
+ return gulp.src(filesToLint)
+ .pipe(jshint())
+ .pipe(jshint.reporter('default'));
+});
+
+// gulp clean: removes js files from dist/ folder
+gulp.task('clean', function (callback) {
+ del(['dist/*.js'], callback);
+});
+
+// gulp build: uglifies and copies the js files to dist/ folder
+gulp.task('build', ['lint', 'clean'], function () {
+ gulp.src('src/*.js')
+ .pipe(gulp.dest('dist'))
+ .pipe(uglify())
+ .pipe(rename('mediawiki-storage.min.js'))
+ .pipe(gulp.dest('dist'));
+});
+
+// gulp: executes build task
+gulp.task('default', ['build'], function() {});
diff --git a/karma.conf.js b/karma.conf.js
new file mode 100644
index 0000000..c0dc637
--- /dev/null
+++ b/karma.conf.js
@@ -0,0 +1,64 @@
+module.exports = function(config) {
+ config.set({
+
+ // base path that will be used to resolve all patterns (eg. files, exclude)
+ basePath: '',
+
+
+ // frameworks to use
+ // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
+ frameworks: ['jasmine', 'sinon'],
+
+
+ // list of files / patterns to load in the browser
+ files: [
+ 'src/bower_modules/jquery/dist/jquery.js',
+ 'src/mediawiki-storage.js',
+ 'test/mediawiki-storage-spec.js'
+ ],
+
+
+ // list of files to exclude
+ exclude: [
+ ],
+
+
+ // preprocess matching files before serving them to the browser
+ // available preprocessors:
https://npmjs.org/browse/keyword/karma-preprocessor
+ preprocessors: {
+ },
+
+
+ // test results reporter to use
+ // possible values: 'dots', 'progress'
+ // available reporters: https://npmjs.org/browse/keyword/karma-reporter
+ reporters: ['progress'],
+
+
+ // web server port
+ port: 9876,
+
+
+ // enable / disable colors in the output (reporters and logs)
+ colors: true,
+
+
+ // level of logging
+ // possible values: config.LOG_DISABLE || config.LOG_ERROR ||
config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
+ logLevel: config.LOG_INFO,
+
+
+ // enable / disable watching file and executing tests whenever any file
changes
+ autoWatch: true,
+
+
+ // start these browsers
+ // available browser launchers:
https://npmjs.org/browse/keyword/karma-launcher
+ browsers: ['Chrome'],
+
+
+ // Continuous Integration mode
+ // if true, Karma captures browsers, runs the tests and exits
+ singleRun: false
+ });
+};
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..e222011
--- /dev/null
+++ b/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "mediawiki-storage",
+ "version": "0.0.0",
+ "devDependencies": {
+ "del": "^0.1.3",
+ "gulp": "^3.8.10",
+ "gulp-jshint": "^1.9.0",
+ "gulp-rename": "^1.2.0",
+ "gulp-uglify": "^1.0.1",
+ "jasmine-core": "^2.1.2",
+ "karma": "^0.12.25",
+ "karma-chrome-launcher": "^0.1.5",
+ "karma-jasmine": "^0.3.1",
+ "karma-sinon": "^1.0.3",
+ "sinon": "^1.12.1"
+ }
+}
diff --git a/src/mediawiki-storage.js b/src/mediawiki-storage.js
new file mode 100644
index 0000000..70c2e42
--- /dev/null
+++ b/src/mediawiki-storage.js
@@ -0,0 +1,145 @@
+'use strict';
+
+(function(global){
+
+ var MediawikiStorage = function () {};
+
+ /**
+ * Returns the contents of the specified mediawiki page
+ *
+ * The mediawiki page is specified using mediawiki's host
+ * (i.e. www.wikipedia.org) and either:
+ * - the page name
+ * - the page id
+ * - the revision id
+ *
+ * Note that:
+ * The page contents must be valid json.
+ * The retrieval of the page contents is done via jsonp.
+ * The return value is passed as parameter for the success callback.
+ * Errors occurring before jsonp call (TypeError) will be thrown
+ * synchronously, and errors occurring within or after jsonp call
+ * will be handed as parameter for error callback.
+ *
+ * Parameter: options {object}
+ * {
+ * host: {string}, // i.e. www.wikipedia.org
+ * // at least one of the following three:
+ * pageName: {string},
+ * pageId: {string},
+ * revId: {string},
+ * success: {function}, // callback [optional]
+ * // parameter: object with page contents
+ * error: {function} // callback [optional]
+ * // parameter: error thrown
+ * }
+ */
+ MediawikiStorage.prototype.get = function (options) {
+ if (typeof options !== 'object') {
+ throw new TypeError('function must receive an object');
+ }
+
+ var url = this._createQueryUrl(options);
+ var that = this;
+
+ $.ajax({
+ url: url,
+ dataType: 'jsonp',
+ contentType: 'application/json',
+
+ success: function (data) {
+ if (typeof options.success === 'function') {
+ var pageJson;
+ try {
+ pageJson = that._getPageJson(data);
+ } catch (e) {
+ return options.error(e);
+ }
+ options.success(pageJson);
+ }
+ },
+
+ error: function (jqXHR, textStatus, errorThrown) {
+ if (typeof options.error === 'function') {
+ options.error(errorThrown);
+ }
+ }
+ });
+ };
+
+ /**
+ * Given a host and a page identifier, creates
+ * a url for querying mediawiki's api for that page
+ */
+ MediawikiStorage.prototype._createQueryUrl = function (options) {
+ if (typeof options.host !== 'string') {
+ throw new TypeError('host must be a string');
+ }
+
+ // mediawiki api can be queried using three types of ids
+ // page names, page ids and revision ids
+ var filter;
+ if (typeof options.pageName === 'string') {
+ filter = '&titles=' + options.pageName;
+ } else if (typeof options.pageId === 'string') {
+ filter = '&pageids=' + options.pageId;
+ } else if (typeof options.revId === 'string') {
+ filter = '&revids=' + options.revId;
+ } else {
+ throw new TypeError(
+ 'one of (pageName|pageId|revId) must be a string'
+ );
+ }
+
+ // for reference, have a look at:
+ // http://www.mediawiki.org/wiki/API:Query
+ return [
+ 'http://',
+ options.host,
+ '/w/api.php',
+ '?action=query',
+ '&prop=revisions',
+ '&format=json',
+ '&rvprop=content',
+ filter
+ ].join('');
+ };
+
+ /**
+ * Given the result of mediawiki api query on a json formatted page
+ * extracts the contents of the page and parses them into an object
+ */
+ MediawikiStorage.prototype._getPageJson = function (data) {
+ var pageContent, result;
+
+ try {
+ var pages = data.query.pages;
+ var pageId = Object.keys(pages)[0];
+ pageContent = pages[pageId].revisions[0]['*'];
+ } catch (e) {
+ throw new SyntaxError('unexpected query result');
+ }
+
+ try {
+ result = JSON.parse(pageContent);
+ } catch (e) {
+ throw new SyntaxError('page contents are not a valid json');
+ }
+
+ return result;
+ };
+
+ var mediawikiStorage = new MediawikiStorage();
+
+ // exports to multiple environments
+ if(typeof define === 'function' && define.amd){ // AMD
+ define(function () { return mediawikiStorage; });
+ } else if (typeof module !== 'undefined' && module.exports){ // node
+ module.exports = mediawikiStorage;
+ } else { // browser
+ // use string because of Google closure compiler ADVANCED_MODE
+ /* jslint sub:true */
+ global['mediawikiStorage'] = mediawikiStorage;
+ }
+
+}(window));
diff --git a/test/mediawiki-storage-spec.js b/test/mediawiki-storage-spec.js
new file mode 100644
index 0000000..ef1277b
--- /dev/null
+++ b/test/mediawiki-storage-spec.js
@@ -0,0 +1,140 @@
+'use strict';
+
+describe('get method', function() {
+
+ var commonUrl = (
+ 'http://www.wikimedia.org/w/api.php' +
+ '?action=query&prop=revisions&format=json&rvprop=content'
+ );
+
+ it('creates a valid query url with pageName', function () {
+ var url = mediawikiStorage._createQueryUrl({
+ host : 'www.wikimedia.org',
+ pageName : 'Schema:EventCapsule'
+ });
+ expect(url).toEqual(commonUrl + '&titles=Schema:EventCapsule');
+ });
+
+ it('creates a valid query url with pageId', function () {
+ var url = mediawikiStorage._createQueryUrl({
+ host : 'www.wikimedia.org',
+ pageId : '12345'
+ });
+ expect(url).toEqual(commonUrl + '&pageids=12345');
+ });
+
+ it('creates a valid query url with revId', function () {
+ var url = mediawikiStorage._createQueryUrl({
+ host : 'www.wikimedia.org',
+ revId : '67890'
+ });
+ expect(url).toEqual(commonUrl + '&revids=67890');
+ });
+
+ it('throws a TypeError when options is not an object', function () {
+ try {
+ mediawikiStorage.get();
+ } catch (e) {
+ expect(e.name).toEqual('TypeError');
+ expect(e.message).toEqual('function must receive an object');
+ }
+ });
+
+ it('throws a TypeError when host is not a string', function () {
+ try {
+ mediawikiStorage.get({});
+ } catch (e) {
+ expect(e.name).toEqual('TypeError');
+ expect(e.message).toEqual('host must be a string');
+ }
+ });
+
+ it('throws a TypeError when pageName, pageId and revId are missing',
function () {
+ try {
+ mediawikiStorage.get({host: 'some.host'});
+ } catch (e) {
+ expect(e.name).toEqual('TypeError');
+ expect(e.message).toEqual('one of (pageName|pageId|revId) must be
a string');
+ }
+ });
+
+ it('returns a SyntaxError when the query result is not expected', function
(done) {
+ sinon.stub($, 'ajax', function (options) {
+ options.success('bad query result');
+ });
+ mediawikiStorage.get({
+ host : 'www.wikimedia.org',
+ pageName : 'Schema:EventCapsule',
+ success : function () {
+ expect(0).toEqual(1); // should never get here
+ },
+ error : function (error) {
+ expect(error.name).toEqual('SyntaxError');
+ expect(error.message).toEqual('unexpected query result');
+ $.ajax.restore();
+ done();
+ }
+ });
+ });
+
+ it('returns a SyntaxError when the page is not a valid json', function
(done) {
+ sinon.stub($, 'ajax', function (options) {
+ options.success(
+ {query:{pages:{'12345':{revisions:[{'*':'not a valid
json'}]}}}}
+ );
+ });
+ mediawikiStorage.get({
+ host : 'www.wikimedia.org',
+ pageName : 'Schema:EventCapsule',
+ success : function () {
+ expect(0).toEqual(1); // should never get here
+ },
+ error : function (error) {
+ expect(error.name).toEqual('SyntaxError');
+ expect(error.message).toEqual('page contents are not a valid
json');
+ $.ajax.restore();
+ done();
+ }
+ });
+ });
+
+ it('propagates any jQuery.ajax errors', function (done) {
+ sinon.stub($, 'ajax', function (options) {
+ options.error({}, 'someStatus', new Error('jQuery.ajax error'));
+ });
+ mediawikiStorage.get({
+ host : 'www.wikimedia.org',
+ pageName : 'Schema:EventCapsule',
+ success : function () {
+ expect(0).toEqual(1); // should never get here
+ },
+ error : function (error) {
+ expect(error.name).toEqual('Error');
+ expect(error.message).toEqual('jQuery.ajax error');
+ $.ajax.restore();
+ done();
+ }
+ });
+ });
+
+ it('returns object created from page json', function (done) {
+ sinon.stub($, 'ajax', function (options) {
+ options.success(
+ {query:{pages:{'12345':{revisions:[{'*':'{"valid":
"json"}'}]}}}}
+ );
+ });
+ mediawikiStorage.get({
+ host : 'www.wikimedia.org',
+ pageName : 'Schema:EventCapsule',
+ success : function (data, textStatus, jqXHR) {
+ expect(data).toEqual({"valid": "json"});
+ $.ajax.restore();
+ done();
+ },
+ error : function () {
+ expect(0).toEqual(1); // should never get here
+ }
+ });
+ });
+
+});
--
To view, visit https://gerrit.wikimedia.org/r/175467
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings
Gerrit-MessageType: merged
Gerrit-Change-Id: I8f94f9f5df7f2146e25b1d08a21d77b91a59f9d1
Gerrit-PatchSet: 4
Gerrit-Project: analytics/mediawiki-storage
Gerrit-Branch: master
Gerrit-Owner: Mforns <[email protected]>
Gerrit-Reviewer: Mforns <[email protected]>
Gerrit-Reviewer: Milimetric <[email protected]>
Gerrit-Reviewer: Nuria <[email protected]>
_______________________________________________
MediaWiki-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits