mediawiki.user: Implement mw.user.stickyRandomId
authorGilles Dubuc <gilles@wikimedia.org>
Thu, 22 Mar 2018 13:06:56 +0000 (14:06 +0100)
committerGilles Dubuc <gilles@wikimedia.org>
Mon, 26 Mar 2018 16:56:31 +0000 (18:56 +0200)
This is a sticky version of generateRandomSessionId,
useful to keep track of the pageview between extensions.

Bug: T187299
Change-Id: I0877c399c60d3fb2fdf8e844cad6acecf6f704c9

resources/src/mediawiki/mediawiki.user.js
tests/qunit/suites/resources/mediawiki/mediawiki.user.test.js

index 65e9e41..5fc1990 100644 (file)
@@ -4,7 +4,7 @@
  */
 /* global Uint32Array */
 ( function ( mw, $ ) {
-       var userInfoPromise;
+       var userInfoPromise, stickyRandomSessionId;
 
        /**
         * Get the current user's groups or rights
@@ -48,7 +48,7 @@
                                // Support: IE 11
                                crypto = window.crypto || window.msCrypto;
 
-                       if ( crypto && crypto.getRandomValues ) {
+                       if ( crypto && crypto.getRandomValues && typeof Uint32Array === 'function' ) {
                                // Fill an array with 2 random values, each of which is 32 bits.
                                // Note that Uint32Array is array-like but does not implement Array.
                                rnds = new Uint32Array( 2 );
                        return hexRnds.join( '' );
                },
 
+               /**
+                * A sticky generateRandomSessionId for the current JS execution context,
+                * cached within this class.
+                *
+                * @return {string} 64 bit integer in hex format, padded
+                */
+               stickyRandomId: function () {
+                       if ( !stickyRandomSessionId ) {
+                               stickyRandomSessionId = mw.user.generateRandomSessionId();
+                       }
+
+                       return stickyRandomSessionId;
+               },
+
                /**
                 * Get the current user's database id
                 *
index bc12642..814a207 100644 (file)
                assert.notEqual( result, result2, 'different when called multiple times' );
        } );
 
+       QUnit.test( 'stickyRandomId', function ( assert ) {
+               var result = mw.user.stickyRandomId(),
+                       result2 = mw.user.stickyRandomId();
+               assert.equal( typeof result, 'string', 'type' );
+               assert.strictEqual( /^[a-f0-9]{16}$/.test( result ), true, '16 HEX symbols string' );
+               assert.equal( result2, result, 'sticky' );
+       } );
+
        QUnit.test( 'sessionId', function ( assert ) {
                var result = mw.user.sessionId(),
                        result2 = mw.user.sessionId();