| 1 |
'use strict'; |
| 2 |
|
| 3 |
const REGISTRATION_KEY = Symbol('@@any-observable/REGISTRATION'); |
| 4 |
|
| 5 |
let isRegistered; |
| 6 |
|
| 7 |
module.exports = (global, loadImplementation) => { |
| 8 |
return (implementation, options = {}) => { |
| 9 |
// Global registration unless explicitly `{global: false}`` in options (default true) |
| 10 |
const registerGlobal = options.global !== false; |
| 11 |
|
| 12 |
// Load any previous global registration |
| 13 |
if (registerGlobal && !isRegistered) { |
| 14 |
isRegistered = global[REGISTRATION_KEY]; |
| 15 |
} |
| 16 |
|
| 17 |
if (isRegistered && implementation && isRegistered.implementation !== implementation) { |
| 18 |
throw new Error(`any-observable already defined as \`${isRegistered.implementation}\`. You can only register an implementation before the first call to \`require('any-observable')\` and an implementation cannot be changed`); |
| 19 |
} |
| 20 |
|
| 21 |
if (!isRegistered) { |
| 22 |
// Use provided implementation |
| 23 |
if (implementation && options.Observable) { |
| 24 |
isRegistered = { |
| 25 |
Observable: options.Observable, |
| 26 |
implementation |
| 27 |
}; |
| 28 |
} else { |
| 29 |
// Require implementation if implementation is specified but not provided |
| 30 |
isRegistered = loadImplementation(implementation); |
| 31 |
} |
| 32 |
|
| 33 |
if (registerGlobal) { |
| 34 |
// Register preference globally in case multiple installations |
| 35 |
global[REGISTRATION_KEY] = isRegistered; |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
return isRegistered; |
| 40 |
}; |
| 41 |
}; |