InstallationController.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * Copyright (c) 2015-present, Parse, LLC.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. *
  9. * @flow
  10. */
  11. import Storage from './Storage';
  12. let iidCache = null;
  13. function hexOctet() {
  14. return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
  15. }
  16. function generateId() {
  17. return hexOctet() + hexOctet() + '-' + hexOctet() + '-' + hexOctet() + '-' + hexOctet() + '-' + hexOctet() + hexOctet() + hexOctet();
  18. }
  19. const InstallationController = {
  20. currentInstallationId()
  21. /*: Promise<string>*/
  22. {
  23. if (typeof iidCache === 'string') {
  24. return Promise.resolve(iidCache);
  25. }
  26. const path = Storage.generatePath('installationId');
  27. return Storage.getItemAsync(path).then(iid => {
  28. if (!iid) {
  29. iid = generateId();
  30. return Storage.setItemAsync(path, iid).then(() => {
  31. iidCache = iid;
  32. return iid;
  33. });
  34. }
  35. iidCache = iid;
  36. return iid;
  37. });
  38. },
  39. _clearCache() {
  40. iidCache = null;
  41. },
  42. _setInstallationIdCache(iid
  43. /*: string*/
  44. ) {
  45. iidCache = iid;
  46. }
  47. };
  48. module.exports = InstallationController;