getToken.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. class Auth {
  2. static _getKey() {
  3. return '__DEEP_RACER_TOKEN';
  4. }
  5. static _eventList = [];
  6. static get() {
  7. const res = localStorage.getItem(this._getKey());
  8. if (res) {
  9. try {
  10. return JSON.parse(res);
  11. } catch {
  12. return null;
  13. }
  14. }
  15. return null;
  16. }
  17. /**
  18. * 默认是追加数据,这样方便设置 schoolId
  19. */
  20. static set(auth, append = true) {
  21. let value = append ? this.get() : auth;
  22. if (append) {
  23. if (value) {
  24. value = {
  25. ...value,
  26. ...auth,
  27. };
  28. } else {
  29. value = auth;
  30. }
  31. }
  32. localStorage.setItem(this._getKey(), JSON.stringify(value));
  33. for (const callback of this._eventList) {
  34. callback(value);
  35. }
  36. }
  37. static remove() {
  38. localStorage.removeItem(this._getKey());
  39. for (const callback of this._eventList) {
  40. callback(null);
  41. }
  42. }
  43. static addListener(callback) {
  44. this._eventList.push(callback);
  45. window.addEventListener('storage', (e) => {
  46. if (e.key === this._getKey()) {
  47. callback(e.newValue ? JSON.parse(e.newValue) : null);
  48. }
  49. });
  50. }
  51. }
  52. window.Auth = Auth;